CoerceToBoolExpression.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. Expression = require("./Expression");
  20. proto.optimize = function optimize() {
  21. this.expression = this.expression.optimize(); // optimize the operand
  22. // if the operand already produces a boolean, then we don't need this
  23. // LATER - Expression to support a "typeof" query?
  24. var expr = this.expression;
  25. if(expr instanceof AndExpression ||
  26. expr instanceof OrExpression ||
  27. expr instanceof NotExpression ||
  28. expr instanceof CoerceToBoolExpression)
  29. return expr;
  30. return this;
  31. };
  32. proto.addDependencies = function addDependencies(deps, path) {
  33. return this.expression.addDependencies(deps);
  34. };
  35. // PROTOTYPE MEMBERS
  36. proto.evaluateInternal = function evaluateInternal(vars){
  37. var result = this.expression.evaluateInternal(vars);
  38. return Value.coerceToBool(result);
  39. };
  40. proto.serialize = function serialize(explain) {
  41. if ( explain ) {
  42. return {$coerceToBool:[this.expression.toJSON()]};
  43. }
  44. else {
  45. return {$and:[this.expression.toJSON()]};
  46. }
  47. };
  48. proto.toJSON = function toJSON() {
  49. // Serializing as an $and expression which will become a CoerceToBool
  50. return {$and:[this.expression.toJSON()]};
  51. };
  52. //TODO: proto.addToBsonObj --- may be required for $project to work
  53. //TODO: proto.addToBsonArray