CoerceToBoolExpression.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. /**
  3. * internal expression for coercing things to booleans
  4. * @class CoerceToBoolExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var CoerceToBoolExpression = module.exports = function CoerceToBoolExpression(expression){
  10. if (arguments.length !== 1) throw new Error("args expected: expression");
  11. this.expression = expression;
  12. base.call(this);
  13. }, klass = CoerceToBoolExpression, base = require("./Expression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. // DEPENDENCIES
  15. var Value = require("../Value"),
  16. AndExpression = require("./AndExpression"),
  17. OrExpression = require("./OrExpression"),
  18. NotExpression = require("./NotExpression");
  19. // PROTOTYPE MEMBERS
  20. proto.evaluate = function evaluate(doc){
  21. var result = this.expression.evaluate(doc);
  22. return Value.coerceToBool(result);
  23. };
  24. proto.optimize = function optimize() {
  25. this.expression = this.expression.optimize(); // optimize the operand
  26. // if the operand already produces a boolean, then we don't need this
  27. // LATER - Expression to support a "typeof" query?
  28. var expr = this.expression;
  29. if(expr instanceof AndExpression ||
  30. expr instanceof OrExpression ||
  31. expr instanceof NotExpression ||
  32. expr instanceof CoerceToBoolExpression)
  33. return expr;
  34. return this;
  35. };
  36. proto.addDependencies = function addDependencies(deps, path) {
  37. return this.expression.addDependencies(deps);
  38. };
  39. proto.toJSON = function toJSON() {
  40. // Serializing as an $and expression which will become a CoerceToBool
  41. return {$and:[this.expression.toJSON()]};
  42. };
  43. //TODO: proto.addToBsonObj --- may be required for $project to work
  44. //TODO: proto.addToBsonArray