AggregationCursor.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseError = require('../error/mongooseError');
  6. const Readable = require('stream').Readable;
  7. const promiseOrCallback = require('../helpers/promiseOrCallback');
  8. const eachAsync = require('../helpers/cursor/eachAsync');
  9. const immediate = require('../helpers/immediate');
  10. const util = require('util');
  11. /**
  12. * An AggregationCursor is a concurrency primitive for processing aggregation
  13. * results one document at a time. It is analogous to QueryCursor.
  14. *
  15. * An AggregationCursor fulfills the Node.js streams3 API,
  16. * in addition to several other mechanisms for loading documents from MongoDB
  17. * one at a time.
  18. *
  19. * Creating an AggregationCursor executes the model's pre aggregate hooks,
  20. * but **not** the model's post aggregate hooks.
  21. *
  22. * Unless you're an advanced user, do **not** instantiate this class directly.
  23. * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead.
  24. *
  25. * @param {Aggregate} agg
  26. * @param {Object} options
  27. * @inherits Readable
  28. * @event `cursor`: Emitted when the cursor is created
  29. * @event `error`: Emitted when an error occurred
  30. * @event `data`: Emitted when the stream is flowing and the next doc is ready
  31. * @event `end`: Emitted when the stream is exhausted
  32. * @api public
  33. */
  34. function AggregationCursor(agg) {
  35. // set autoDestroy=true because on node 12 it's by default false
  36. // gh-10902 need autoDestroy to destroy correctly and emit 'close' event
  37. Readable.call(this, { autoDestroy: true, objectMode: true });
  38. this.cursor = null;
  39. this.agg = agg;
  40. this._transforms = [];
  41. const model = agg._model;
  42. delete agg.options.cursor.useMongooseAggCursor;
  43. this._mongooseOptions = {};
  44. _init(model, this, agg);
  45. }
  46. util.inherits(AggregationCursor, Readable);
  47. /*!
  48. * ignore
  49. */
  50. function _init(model, c, agg) {
  51. if (!model.collection.buffer) {
  52. model.hooks.execPre('aggregate', agg, function() {
  53. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  54. c.emit('cursor', c.cursor);
  55. });
  56. } else {
  57. model.collection.emitter.once('queue', function() {
  58. model.hooks.execPre('aggregate', agg, function() {
  59. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  60. c.emit('cursor', c.cursor);
  61. });
  62. });
  63. }
  64. }
  65. /*!
  66. * Necessary to satisfy the Readable API
  67. */
  68. AggregationCursor.prototype._read = function() {
  69. const _this = this;
  70. _next(this, function(error, doc) {
  71. if (error) {
  72. return _this.emit('error', error);
  73. }
  74. if (!doc) {
  75. _this.push(null);
  76. _this.cursor.close(function(error) {
  77. if (error) {
  78. return _this.emit('error', error);
  79. }
  80. });
  81. return;
  82. }
  83. _this.push(doc);
  84. });
  85. };
  86. if (Symbol.asyncIterator != null) {
  87. const msg = 'Mongoose does not support using async iterators with an ' +
  88. 'existing aggregation cursor. See http://bit.ly/mongoose-async-iterate-aggregation';
  89. AggregationCursor.prototype[Symbol.asyncIterator] = function() {
  90. throw new MongooseError(msg);
  91. };
  92. }
  93. /**
  94. * Registers a transform function which subsequently maps documents retrieved
  95. * via the streams interface or `.next()`
  96. *
  97. * ####Example
  98. *
  99. * // Map documents returned by `data` events
  100. * Thing.
  101. * find({ name: /^hello/ }).
  102. * cursor().
  103. * map(function (doc) {
  104. * doc.foo = "bar";
  105. * return doc;
  106. * })
  107. * on('data', function(doc) { console.log(doc.foo); });
  108. *
  109. * // Or map documents returned by `.next()`
  110. * const cursor = Thing.find({ name: /^hello/ }).
  111. * cursor().
  112. * map(function (doc) {
  113. * doc.foo = "bar";
  114. * return doc;
  115. * });
  116. * cursor.next(function(error, doc) {
  117. * console.log(doc.foo);
  118. * });
  119. *
  120. * @param {Function} fn
  121. * @return {AggregationCursor}
  122. * @api public
  123. * @method map
  124. */
  125. AggregationCursor.prototype.map = function(fn) {
  126. this._transforms.push(fn);
  127. return this;
  128. };
  129. /*!
  130. * Marks this cursor as errored
  131. */
  132. AggregationCursor.prototype._markError = function(error) {
  133. this._error = error;
  134. return this;
  135. };
  136. /**
  137. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  138. * `next()` will error.
  139. *
  140. * @param {Function} callback
  141. * @return {Promise}
  142. * @api public
  143. * @method close
  144. * @emits close
  145. * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
  146. */
  147. AggregationCursor.prototype.close = function(callback) {
  148. return promiseOrCallback(callback, cb => {
  149. this.cursor.close(error => {
  150. if (error) {
  151. cb(error);
  152. return this.listeners('error').length > 0 && this.emit('error', error);
  153. }
  154. this.emit('close');
  155. cb(null);
  156. });
  157. });
  158. };
  159. /**
  160. * Get the next document from this cursor. Will return `null` when there are
  161. * no documents left.
  162. *
  163. * @param {Function} callback
  164. * @return {Promise}
  165. * @api public
  166. * @method next
  167. */
  168. AggregationCursor.prototype.next = function(callback) {
  169. return promiseOrCallback(callback, cb => {
  170. _next(this, cb);
  171. });
  172. };
  173. /**
  174. * Execute `fn` for every document in the cursor. If `fn` returns a promise,
  175. * will wait for the promise to resolve before iterating on to the next one.
  176. * Returns a promise that resolves when done.
  177. *
  178. * @param {Function} fn
  179. * @param {Object} [options]
  180. * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
  181. * @param {Function} [callback] executed when all docs have been processed
  182. * @return {Promise}
  183. * @api public
  184. * @method eachAsync
  185. */
  186. AggregationCursor.prototype.eachAsync = function(fn, opts, callback) {
  187. const _this = this;
  188. if (typeof opts === 'function') {
  189. callback = opts;
  190. opts = {};
  191. }
  192. opts = opts || {};
  193. return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
  194. };
  195. /**
  196. * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js
  197. * You do not need to call this function explicitly, the JavaScript runtime
  198. * will call it for you.
  199. *
  200. * ####Example
  201. *
  202. * // Async iterator without explicitly calling `cursor()`. Mongoose still
  203. * // creates an AggregationCursor instance internally.
  204. * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
  205. * for await (const doc of agg) {
  206. * console.log(doc.name);
  207. * }
  208. *
  209. * // You can also use an AggregationCursor instance for async iteration
  210. * const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor();
  211. * for await (const doc of cursor) {
  212. * console.log(doc.name);
  213. * }
  214. *
  215. * Node.js 10.x supports async iterators natively without any flags. You can
  216. * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187).
  217. *
  218. * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If
  219. * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
  220. * support async iterators.
  221. *
  222. * @method Symbol.asyncIterator
  223. * @memberOf AggregationCursor
  224. * @instance
  225. * @api public
  226. */
  227. if (Symbol.asyncIterator != null) {
  228. AggregationCursor.prototype[Symbol.asyncIterator] = function() {
  229. return this.transformNull()._transformForAsyncIterator();
  230. };
  231. }
  232. /*!
  233. * ignore
  234. */
  235. AggregationCursor.prototype._transformForAsyncIterator = function() {
  236. if (this._transforms.indexOf(_transformForAsyncIterator) === -1) {
  237. this.map(_transformForAsyncIterator);
  238. }
  239. return this;
  240. };
  241. /*!
  242. * ignore
  243. */
  244. AggregationCursor.prototype.transformNull = function(val) {
  245. if (arguments.length === 0) {
  246. val = true;
  247. }
  248. this._mongooseOptions.transformNull = val;
  249. return this;
  250. };
  251. /*!
  252. * ignore
  253. */
  254. function _transformForAsyncIterator(doc) {
  255. return doc == null ? { done: true } : { value: doc, done: false };
  256. }
  257. /**
  258. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  259. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  260. *
  261. * @param {String} flag
  262. * @param {Boolean} value
  263. * @return {AggregationCursor} this
  264. * @api public
  265. * @method addCursorFlag
  266. */
  267. AggregationCursor.prototype.addCursorFlag = function(flag, value) {
  268. const _this = this;
  269. _waitForCursor(this, function() {
  270. _this.cursor.addCursorFlag(flag, value);
  271. });
  272. return this;
  273. };
  274. /*!
  275. * ignore
  276. */
  277. function _waitForCursor(ctx, cb) {
  278. if (ctx.cursor) {
  279. return cb();
  280. }
  281. ctx.once('cursor', function() {
  282. cb();
  283. });
  284. }
  285. /*!
  286. * Get the next doc from the underlying cursor and mongooseify it
  287. * (populate, etc.)
  288. */
  289. function _next(ctx, cb) {
  290. let callback = cb;
  291. if (ctx._transforms.length) {
  292. callback = function(err, doc) {
  293. if (err || (doc === null && !ctx._mongooseOptions.transformNull)) {
  294. return cb(err, doc);
  295. }
  296. cb(err, ctx._transforms.reduce(function(doc, fn) {
  297. return fn(doc);
  298. }, doc));
  299. };
  300. }
  301. if (ctx._error) {
  302. return immediate(function() {
  303. callback(ctx._error);
  304. });
  305. }
  306. if (ctx.cursor) {
  307. return ctx.cursor.next(function(error, doc) {
  308. if (error) {
  309. return callback(error);
  310. }
  311. if (!doc) {
  312. return callback(null, null);
  313. }
  314. callback(null, doc);
  315. });
  316. } else {
  317. ctx.once('cursor', function() {
  318. _next(ctx, cb);
  319. });
  320. }
  321. }
  322. module.exports = AggregationCursor;