AggregationCursor.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. * var 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. * ignore
  201. */
  202. AggregationCursor.prototype.transformNull = function(val) {
  203. if (arguments.length === 0) {
  204. val = true;
  205. }
  206. this._mongooseOptions.transformNull = val;
  207. return this;
  208. };
  209. /**
  210. * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  211. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  212. *
  213. * @param {String} flag
  214. * @param {Boolean} value
  215. * @return {AggregationCursor} this
  216. * @api public
  217. * @method addCursorFlag
  218. */
  219. AggregationCursor.prototype.addCursorFlag = function(flag, value) {
  220. const _this = this;
  221. _waitForCursor(this, function() {
  222. _this.cursor.addCursorFlag(flag, value);
  223. });
  224. return this;
  225. };
  226. /*!
  227. * ignore
  228. */
  229. function _waitForCursor(ctx, cb) {
  230. if (ctx.cursor) {
  231. return cb();
  232. }
  233. ctx.once('cursor', function() {
  234. cb();
  235. });
  236. }
  237. /*!
  238. * Get the next doc from the underlying cursor and mongooseify it
  239. * (populate, etc.)
  240. */
  241. function _next(ctx, cb) {
  242. let callback = cb;
  243. if (ctx._transforms.length) {
  244. callback = function(err, doc) {
  245. if (err || (doc === null && !ctx._mongooseOptions.transformNull)) {
  246. return cb(err, doc);
  247. }
  248. cb(err, ctx._transforms.reduce(function(doc, fn) {
  249. return fn(doc);
  250. }, doc));
  251. };
  252. }
  253. if (ctx._error) {
  254. return process.nextTick(function() {
  255. callback(ctx._error);
  256. });
  257. }
  258. if (ctx.cursor) {
  259. return ctx.cursor.next(function(error, doc) {
  260. if (error) {
  261. return callback(error);
  262. }
  263. if (!doc) {
  264. return callback(null, null);
  265. }
  266. callback(null, doc);
  267. });
  268. } else {
  269. ctx.once('cursor', function() {
  270. _next(ctx, cb);
  271. });
  272. }
  273. }
  274. module.exports = AggregationCursor;