CoerceToBoolExpression.js 1.8 KB

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