AggregationCursor.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /**
  2. * AggregationCursor provides an interface to pipeline results.
  3. * @class AggregationCursor
  4. * @namespace mungedb-aggregate
  5. * @module mungedb-aggregate
  6. * @constructor
  7. * @param pipelineInst An instance of a pipeline to be run
  8. */
  9. var AggregationCursor = module.exports = function(pipelineInst) {
  10. this.pipelineInst = pipelineInst;
  11. }, klass = AggregationCursor, proto = klass.prototype;
  12. /**
  13. * Return an array of pipeline results
  14. *
  15. * Runs "synchronously" if no callback is given.
  16. * @method toArray
  17. * @param {Function} callback If null, run synchronously
  18. * @return {Array} documents (when no callback is provided)
  19. */
  20. proto.toArray = function(callback) {
  21. var batch = [],
  22. isAsync = typeof callback === "function";
  23. if(!isAsync) return this.pipelineInst.run().result;
  24. this.pipelineInst.run(isAsync, function(err, doc) {
  25. if (err) if (callback) return callback(err); else throw err;
  26. if (doc !== null) return batch.push(doc);
  27. if (callback) return callback(null, batch);
  28. });
  29. if (!callback) return batch;
  30. };
  31. /**
  32. * Run a function on each document result and a callback at the end of the stream.
  33. * @method forEach
  34. * @param {function} iterator Function to be run on each $document
  35. * @param {Function} callback Function run when aggregation is finished
  36. */
  37. proto.forEach = function(iterator, callback) {
  38. this.pipelineInst.run(function(err, doc) {
  39. if (err || doc === null) return callback(err);
  40. iterator(doc);
  41. });
  42. };
  43. /**
  44. * Run a function on each document getting a null to signify EOF.
  45. * @method each
  46. * @param {Function} callback Run for each document until EOF
  47. */
  48. proto.each = function(callback) {
  49. this.pipelineInst.run(callback);
  50. };