CoerceToBoolExpression.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /** Register Expression */
  53. Expression.registerExpression("$coerceToBool",CoerceToBoolExpression.parse);
  54. //TODO: proto.addToBsonObj --- may be required for $project to work
  55. //TODO: proto.addToBsonArray