AggregationCursor.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const Readable = require('stream').Readable;
  6. const eachAsync = require('../helpers/cursor/eachAsync');
  7. const util = require('util');
  8. const utils = require('../utils');
  9. /**
  10. * An AggregationCursor is a concurrency primitive for processing aggregation
  11. * results one document at a time. It is analogous to QueryCursor.
  12. *
  13. * An AggregationCursor fulfills the Node.js streams3 API,
  14. * in addition to several other mechanisms for loading documents from MongoDB
  15. * one at a time.
  16. *
  17. * Creating an AggregationCursor executes the model's pre aggregate hooks,
  18. * but **not** the model's post aggregate hooks.
  19. *
  20. * Unless you're an advanced user, do **not** instantiate this class directly.
  21. * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead.
  22. *
  23. * @param {Aggregate} agg
  24. * @param {Object} options
  25. * @inherits Readable
  26. * @event `cursor`: Emitted when the cursor is created
  27. * @event `error`: Emitted when an error occurred
  28. * @event `data`: Emitted when the stream is flowing and the next doc is ready
  29. * @event `end`: Emitted when the stream is exhausted
  30. * @api public
  31. */
  32. function AggregationCursor(agg) {
  33. Readable.call(this, { objectMode: true });
  34. this.cursor = null;
  35. this.agg = agg;
  36. this._transforms = [];
  37. const model = agg._model;
  38. delete agg.options.cursor.useMongooseAggCursor;
  39. this._mongooseOptions = {};
  40. _init(model, this, agg);
  41. }
  42. util.inherits(AggregationCursor, Readable);
  43. /*!
  44. * ignore
  45. */
  46. function _init(model, c, agg) {
  47. if (!model.collection.buffer) {
  48. model.hooks.execPre('aggregate', agg, function() {
  49. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  50. c.emit('cursor', c.cursor);
  51. });
  52. } else {
  53. model.collection.emitter.once('queue', function() {
  54. model.hooks.execPre('aggregate', agg, function() {
  55. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  56. c.emit('cursor', c.cursor);
  57. });
  58. });
  59. }
  60. }
  61. /*!
  62. * Necessary to satisfy the Readable API
  63. */
  64. AggregationCursor.prototype._read = function() {
  65. const _this = this;
  66. _next(this, function(error, doc) {
  67. if (error) {
  68. return _this.emit('error', error);
  69. }
  70. if (!doc) {
  71. _this.push(null);
  72. _this.cursor.close(function(error) {
  73. if (error) {
  74. return _this.emit('error', error);
  75. }
  76. setTimeout(function() {
  77. _this.emit('close');
  78. }, 0);
  79. });
  80. return;
  81. }
  82. _this.push(doc);
  83. });
  84. };
  85. /**
  86. * Registers a transform function which subsequently maps documents retrieved
  87. * via the streams interface or `.next()`
  88. *
  89. * ####Example
  90. *
  91. * // Map documents returned by `data` events
  92. * Thing.
  93. * find({ name: /^hello/ }).
  94. * cursor().
  95. * map(function (doc) {
  96. * doc.foo = "bar";
  97. * return doc;
  98. * })
  99. * on('data', function(doc) { console.log(doc.foo); });
  100. *
  101. * // Or map documents returned by `.next()`
  102. * var cursor = Thing.find({ name: /^hello/ }).
  103. * cursor().
  104. * map(function (doc) {
  105. * doc.foo = "bar";
  106. * return doc;
  107. * });
  108. * cursor.next(function(error, doc) {
  109. * console.log(doc.foo);
  110. * });
  111. *
  112. * @param {Function} fn
  113. * @return {AggregationCursor}
  114. * @api public
  115. * @method map
  116. */
  117. AggregationCursor.prototype.map = function(fn) {
  118. this._transforms.push(fn);
  119. return this;
  120. };
  121. /*!
  122. * Marks this cursor as errored
  123. */
  124. AggregationCursor.prototype._markError = function(error) {
  125. this._error = error;
  126. return this;
  127. };
  128. /**
  129. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  130. * `next()` will error.
  131. *
  132. * @param {Function} callback
  133. * @return {Promise}
  134. * @api public
  135. * @method close
  136. * @emits close
  137. * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
  138. */
  139. AggregationCursor.prototype.close = function(callback) {
  140. return utils.promiseOrCallback(callback, cb => {
  141. this.cursor.close(error => {
  142. if (error) {
  143. cb(error);
  144. return this.listeners('error').length > 0 && this.emit('error', error);
  145. }
  146. this.emit('close');
  147. cb(null);
  148. });
  149. });
  150. };
  151. /**
  152. * Get the next document from this cursor. Will return `null` when there are
  153. * no documents left.
  154. *
  155. * @param {Function} callback
  156. * @return {Promise}
  157. * @api public
  158. * @method next
  159. */
  160. AggregationCursor.prototype.next = function(callback) {
  161. return utils.promiseOrCallback(callback, cb => {
  162. _next(this, cb);
  163. });
  164. };
  165. /**
  166. * Execute `fn` for every document in the cursor. If `fn` returns a promise,
  167. * will wait for the promise to resolve before iterating on to the next one.
  168. * Returns a promise that resolves when done.
  169. *
  170. * @param {Function} fn
  171. * @param {Object} [options]
  172. * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
  173. * @param {Function} [callback] executed when all docs have been processed
  174. * @return {Promise}
  175. * @api public
  176. * @method eachAsync
  177. */
  178. AggregationCursor.prototype.eachAsync = function(fn, opts, callback) {
  179. const _this = this;
  180. if (typeof opts === 'function') {
  181. callback = opts;
  182. opts = {};
  183. }
  184. opts = opts || {};
  185. return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
  186. };
  187. /*!
  188. * ignore
  189. */
  190. AggregationCursor.prototype.transformNull = function(val) {
  191. if (arguments.length === 0) {
  192. val = true;
  193. }
  194. this._mongooseOptions.transformNull = val;
  195. return this;
  196. };
  197. /**
  198. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  199. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  200. *
  201. * @param {String} flag
  202. * @param {Boolean} value
  203. * @return {AggregationCursor} this
  204. * @api public
  205. * @method addCursorFlag
  206. */
  207. AggregationCursor.prototype.addCursorFlag = function(flag, value) {
  208. const _this = this;
  209. _waitForCursor(this, function() {
  210. _this.cursor.addCursorFlag(flag, value);
  211. });
  212. return this;
  213. };
  214. /*!
  215. * ignore
  216. */
  217. function _waitForCursor(ctx, cb) {
  218. if (ctx.cursor) {
  219. return cb();
  220. }
  221. ctx.once('cursor', function() {
  222. cb();
  223. });
  224. }
  225. /*!
  226. * Get the next doc from the underlying cursor and mongooseify it
  227. * (populate, etc.)
  228. */
  229. function _next(ctx, cb) {
  230. let callback = cb;
  231. if (ctx._transforms.length) {
  232. callback = function(err, doc) {
  233. if (err || (doc === null && !ctx._mongooseOptions.transformNull)) {
  234. return cb(err, doc);
  235. }
  236. cb(err, ctx._transforms.reduce(function(doc, fn) {
  237. return fn(doc);
  238. }, doc));
  239. };
  240. }
  241. if (ctx._error) {
  242. return process.nextTick(function() {
  243. callback(ctx._error);
  244. });
  245. }
  246. if (ctx.cursor) {
  247. return ctx.cursor.next(function(error, doc) {
  248. if (error) {
  249. return callback(error);
  250. }
  251. if (!doc) {
  252. return callback(null, null);
  253. }
  254. callback(null, doc);
  255. });
  256. } else {
  257. ctx.once('cursor', function() {
  258. _next(ctx, cb);
  259. });
  260. }
  261. }
  262. module.exports = AggregationCursor;