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 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. * @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. // set autoDestroy=true because on node 12 it's by default false
  35. // gh-10902 need autoDestroy to destroy correctly and emit 'close' event
  36. Readable.call(this, { autoDestroy: true, objectMode: true });
  37. this.cursor = null;
  38. this.agg = agg;
  39. this._transforms = [];
  40. const model = agg._model;
  41. delete agg.options.cursor.useMongooseAggCursor;
  42. this._mongooseOptions = {};
  43. _init(model, this, agg);
  44. }
  45. util.inherits(AggregationCursor, Readable);
  46. /*!
  47. * ignore
  48. */
  49. function _init(model, c, agg) {
  50. if (!model.collection.buffer) {
  51. model.hooks.execPre('aggregate', agg, function() {
  52. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  53. c.emit('cursor', c.cursor);
  54. });
  55. } else {
  56. model.collection.emitter.once('queue', function() {
  57. model.hooks.execPre('aggregate', agg, function() {
  58. c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {});
  59. c.emit('cursor', c.cursor);
  60. });
  61. });
  62. }
  63. }
  64. /*!
  65. * Necessary to satisfy the Readable API
  66. */
  67. AggregationCursor.prototype._read = function() {
  68. const _this = this;
  69. _next(this, function(error, doc) {
  70. if (error) {
  71. return _this.emit('error', error);
  72. }
  73. if (!doc) {
  74. _this.push(null);
  75. _this.cursor.close(function(error) {
  76. if (error) {
  77. return _this.emit('error', error);
  78. }
  79. });
  80. return;
  81. }
  82. _this.push(doc);
  83. });
  84. };
  85. if (Symbol.asyncIterator != null) {
  86. const msg = 'Mongoose does not support using async iterators with an ' +
  87. 'existing aggregation cursor. See https://bit.ly/mongoose-async-iterate-aggregation';
  88. AggregationCursor.prototype[Symbol.asyncIterator] = function() {
  89. throw new MongooseError(msg);
  90. };
  91. }
  92. /**
  93. * Registers a transform function which subsequently maps documents retrieved
  94. * via the streams interface or `.next()`
  95. *
  96. * #### Example
  97. *
  98. * // Map documents returned by `data` events
  99. * Thing.
  100. * find({ name: /^hello/ }).
  101. * cursor().
  102. * map(function (doc) {
  103. * doc.foo = "bar";
  104. * return doc;
  105. * })
  106. * on('data', function(doc) { console.log(doc.foo); });
  107. *
  108. * // Or map documents returned by `.next()`
  109. * const cursor = Thing.find({ name: /^hello/ }).
  110. * cursor().
  111. * map(function (doc) {
  112. * doc.foo = "bar";
  113. * return doc;
  114. * });
  115. * cursor.next(function(error, doc) {
  116. * console.log(doc.foo);
  117. * });
  118. *
  119. * @param {Function} fn
  120. * @return {AggregationCursor}
  121. * @api public
  122. * @method map
  123. */
  124. Object.defineProperty(AggregationCursor.prototype, 'map', {
  125. value: function(fn) {
  126. this._transforms.push(fn);
  127. return this;
  128. },
  129. enumerable: true,
  130. configurable: true,
  131. writable: true
  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 https://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](https://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 immediate(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;