AggregationCursor.js 9.3 KB

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