AggregationCursor.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. this.pipelineInst.run(function(err, doc) {
  23. if (err && callback) return callback(err), callback = undefined;
  24. if (err && !callback) throw err;
  25. if (doc === null && callback) return callback(null, batch), callback = undefined;
  26. else if (doc !== null) batch.push(doc);
  27. });
  28. if (!callback) return batch;
  29. };
  30. /**
  31. * Run a function on each document result and a callback at the end of the stream.
  32. * @method forEach
  33. * @param {function} iterator Function to be run on each $document
  34. * @param {Function} callback Function run when aggregation is finished
  35. */
  36. proto.forEach = function(iterator, callback) {
  37. this.pipelineInst.run(function(err, doc) {
  38. if (err || doc === null) return callback(err);
  39. iterator(doc);
  40. });
  41. };
  42. /**
  43. * Run a function on each document getting a null to signify EOF.
  44. * @method each
  45. * @param {Function} callback Run for each document until EOF
  46. */
  47. proto.each = function(callback) {
  48. this.pipelineInst.run(callback);
  49. };