UnwindOp.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. var Op = require("../Op");
  2. /** The $unwind operator; opts is the $-prefixed path to the Array to be unwound. **/
  3. var UnwindOp = module.exports = (function(){
  4. // CONSTRUCTOR
  5. var base = Op, proto, klass = function UnwindOp(opts){
  6. if(!opts || opts[0] != "$")
  7. throw new Error("$unwind: field path references must be prefixed with a '$' (" + JSON.stringify(opts) + "); code 15982");
  8. this.path = opts.substr(1).split(".");
  9. base.call(this, opts);
  10. };
  11. proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  12. // PROTOTYPE MEMBERS
  13. proto.write = function writeUnwound(obj){
  14. var t = traverse(obj),
  15. val = t.get(this.path);
  16. if(val !== undefined){
  17. if(val.constructor.name !== "Array")
  18. throw new Error("$unwind: value at end of field path must be an array; code 15978");
  19. else{
  20. t.set(this.path, null); // temporarily set this to null to avoid needlessly cloning it below
  21. for(var i = 0, l = val.length; i < l; i++){
  22. var o = t.clone();
  23. traverse(o).set(this.path, val[i]);
  24. this.queue(o);
  25. }
  26. t.set(this.path, val); // be nice and put this back on the original just in case somebody cares
  27. }
  28. }
  29. };
  30. return klass;
  31. })();