AggregationCursor.js 9.3 KB

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