QueryCursor.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const Readable = require('stream').Readable;
  6. const promiseOrCallback = require('../helpers/promiseOrCallback');
  7. const eachAsync = require('../helpers/cursor/eachAsync');
  8. const helpers = require('../queryhelpers');
  9. const immediate = require('../helpers/immediate');
  10. const util = require('util');
  11. /**
  12. * A QueryCursor is a concurrency primitive for processing query results
  13. * one document at a time. A QueryCursor fulfills the Node.js streams3 API,
  14. * in addition to several other mechanisms for loading documents from MongoDB
  15. * one at a time.
  16. *
  17. * QueryCursors execute the model's pre `find` hooks before loading any documents
  18. * from MongoDB, and the model's post `find` hooks after loading each document.
  19. *
  20. * Unless you're an advanced user, do **not** instantiate this class directly.
  21. * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead.
  22. *
  23. * @param {Query} query
  24. * @param {Object} options query options passed to `.find()`
  25. * @inherits Readable
  26. * @event `cursor`: Emitted when the cursor is created
  27. * @event `error`: Emitted when an error occurred
  28. * @event `data`: Emitted when the stream is flowing and the next doc is ready
  29. * @event `end`: Emitted when the stream is exhausted
  30. * @api public
  31. */
  32. function QueryCursor(query, options) {
  33. // set autoDestroy=true because on node 12 it's by default false
  34. // gh-10902 need autoDestroy to destroy correctly and emit 'close' event
  35. Readable.call(this, { autoDestroy: true, objectMode: true });
  36. this.cursor = null;
  37. this.query = query;
  38. const _this = this;
  39. const model = query.model;
  40. this._mongooseOptions = {};
  41. this._transforms = [];
  42. this.model = model;
  43. this.options = options || {};
  44. model.hooks.execPre('find', query, (err) => {
  45. if (err != null) {
  46. _this._markError(err);
  47. _this.listeners('error').length > 0 && _this.emit('error', err);
  48. return;
  49. }
  50. this._transforms = this._transforms.concat(query._transforms.slice());
  51. if (this.options.transform) {
  52. this._transforms.push(options.transform);
  53. }
  54. // Re: gh-8039, you need to set the `cursor.batchSize` option, top-level
  55. // `batchSize` option doesn't work.
  56. if (this.options.batchSize) {
  57. this.options.cursor = options.cursor || {};
  58. this.options.cursor.batchSize = options.batchSize;
  59. // Max out the number of documents we'll populate in parallel at 5000.
  60. this.options._populateBatchSize = Math.min(this.options.batchSize, 5000);
  61. }
  62. model.collection.find(query._conditions, this.options, (err, cursor) => {
  63. if (err != null) {
  64. _this._markError(err);
  65. _this.listeners('error').length > 0 && _this.emit('error', _this._error);
  66. return;
  67. }
  68. if (_this._error) {
  69. cursor.close(function() {});
  70. _this.listeners('error').length > 0 && _this.emit('error', _this._error);
  71. }
  72. _this.cursor = cursor;
  73. _this.emit('cursor', cursor);
  74. });
  75. });
  76. }
  77. util.inherits(QueryCursor, Readable);
  78. /*!
  79. * Necessary to satisfy the Readable API
  80. */
  81. QueryCursor.prototype._read = function() {
  82. const _this = this;
  83. _next(this, function(error, doc) {
  84. if (error) {
  85. return _this.emit('error', error);
  86. }
  87. if (!doc) {
  88. _this.push(null);
  89. _this.cursor.close(function(error) {
  90. if (error) {
  91. return _this.emit('error', error);
  92. }
  93. });
  94. return;
  95. }
  96. _this.push(doc);
  97. });
  98. };
  99. /**
  100. * Registers a transform function which subsequently maps documents retrieved
  101. * via the streams interface or `.next()`
  102. *
  103. * #### Example
  104. *
  105. * // Map documents returned by `data` events
  106. * Thing.
  107. * find({ name: /^hello/ }).
  108. * cursor().
  109. * map(function (doc) {
  110. * doc.foo = "bar";
  111. * return doc;
  112. * })
  113. * on('data', function(doc) { console.log(doc.foo); });
  114. *
  115. * // Or map documents returned by `.next()`
  116. * const cursor = Thing.find({ name: /^hello/ }).
  117. * cursor().
  118. * map(function (doc) {
  119. * doc.foo = "bar";
  120. * return doc;
  121. * });
  122. * cursor.next(function(error, doc) {
  123. * console.log(doc.foo);
  124. * });
  125. *
  126. * @param {Function} fn
  127. * @return {QueryCursor}
  128. * @api public
  129. * @method map
  130. */
  131. Object.defineProperty(QueryCursor.prototype, 'map', {
  132. value: function(fn) {
  133. this._transforms.push(fn);
  134. return this;
  135. },
  136. enumerable: true,
  137. configurable: true,
  138. writable: true
  139. });
  140. /*!
  141. * Marks this cursor as errored
  142. */
  143. QueryCursor.prototype._markError = function(error) {
  144. this._error = error;
  145. return this;
  146. };
  147. /**
  148. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  149. * `next()` will error.
  150. *
  151. * @param {Function} callback
  152. * @return {Promise}
  153. * @api public
  154. * @method close
  155. * @emits close
  156. * @see MongoDB driver cursor#close https://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
  157. */
  158. QueryCursor.prototype.close = function(callback) {
  159. return promiseOrCallback(callback, cb => {
  160. this.cursor.close(error => {
  161. if (error) {
  162. cb(error);
  163. return this.listeners('error').length > 0 && this.emit('error', error);
  164. }
  165. this.emit('close');
  166. cb(null);
  167. });
  168. }, this.model.events);
  169. };
  170. /**
  171. * Get the next document from this cursor. Will return `null` when there are
  172. * no documents left.
  173. *
  174. * @param {Function} callback
  175. * @return {Promise}
  176. * @api public
  177. * @method next
  178. */
  179. QueryCursor.prototype.next = function(callback) {
  180. return promiseOrCallback(callback, cb => {
  181. _next(this, function(error, doc) {
  182. if (error) {
  183. return cb(error);
  184. }
  185. cb(null, doc);
  186. });
  187. }, this.model.events);
  188. };
  189. /**
  190. * Execute `fn` for every document in the cursor. If `fn` returns a promise,
  191. * will wait for the promise to resolve before iterating on to the next one.
  192. * Returns a promise that resolves when done.
  193. *
  194. * #### Example
  195. *
  196. * // Iterate over documents asynchronously
  197. * Thing.
  198. * find({ name: /^hello/ }).
  199. * cursor().
  200. * eachAsync(async function (doc, i) {
  201. * doc.foo = doc.bar + i;
  202. * await doc.save();
  203. * })
  204. *
  205. * @param {Function} fn
  206. * @param {Object} [options]
  207. * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
  208. * @param {Number} [options.batchSize] if set, will call `fn()` with arrays of documents with length at most `batchSize`
  209. * @param {Boolean} [options.continueOnError=false] if true, `eachAsync()` iterates through all docs even if `fn` throws an error. If false, `eachAsync()` throws an error immediately if the given function `fn()` throws an error.
  210. * @param {Function} [callback] executed when all docs have been processed
  211. * @return {Promise}
  212. * @api public
  213. * @method eachAsync
  214. */
  215. QueryCursor.prototype.eachAsync = function(fn, opts, callback) {
  216. const _this = this;
  217. if (typeof opts === 'function') {
  218. callback = opts;
  219. opts = {};
  220. }
  221. opts = opts || {};
  222. return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
  223. };
  224. /**
  225. * The `options` passed in to the `QueryCursor` constructor.
  226. *
  227. * @api public
  228. * @property options
  229. */
  230. QueryCursor.prototype.options;
  231. /**
  232. * Adds a [cursor flag](https://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
  233. * Useful for setting the `noCursorTimeout` and `tailable` flags.
  234. *
  235. * @param {String} flag
  236. * @param {Boolean} value
  237. * @return {AggregationCursor} this
  238. * @api public
  239. * @method addCursorFlag
  240. */
  241. QueryCursor.prototype.addCursorFlag = function(flag, value) {
  242. const _this = this;
  243. _waitForCursor(this, function() {
  244. _this.cursor.addCursorFlag(flag, value);
  245. });
  246. return this;
  247. };
  248. /*!
  249. * ignore
  250. */
  251. QueryCursor.prototype.transformNull = function(val) {
  252. if (arguments.length === 0) {
  253. val = true;
  254. }
  255. this._mongooseOptions.transformNull = val;
  256. return this;
  257. };
  258. /*!
  259. * ignore
  260. */
  261. QueryCursor.prototype._transformForAsyncIterator = function() {
  262. if (this._transforms.indexOf(_transformForAsyncIterator) === -1) {
  263. this.map(_transformForAsyncIterator);
  264. }
  265. return this;
  266. };
  267. /**
  268. * Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js).
  269. * You do not need to call this function explicitly, the JavaScript runtime
  270. * will call it for you.
  271. *
  272. * #### Example
  273. *
  274. * // Works without using `cursor()`
  275. * for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
  276. * console.log(doc.name);
  277. * }
  278. *
  279. * // Can also use `cursor()`
  280. * for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) {
  281. * console.log(doc.name);
  282. * }
  283. *
  284. * Node.js 10.x supports async iterators natively without any flags. You can
  285. * 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).
  286. *
  287. * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If
  288. * `Symbol.asyncIterator` is undefined, that means your Node.js version does not
  289. * support async iterators.
  290. *
  291. * @method Symbol.asyncIterator
  292. * @memberOf Query
  293. * @instance
  294. * @api public
  295. */
  296. if (Symbol.asyncIterator != null) {
  297. QueryCursor.prototype[Symbol.asyncIterator] = function() {
  298. return this.transformNull()._transformForAsyncIterator();
  299. };
  300. }
  301. /*!
  302. * ignore
  303. */
  304. function _transformForAsyncIterator(doc) {
  305. return doc == null ? { done: true } : { value: doc, done: false };
  306. }
  307. /*!
  308. * Get the next doc from the underlying cursor and mongooseify it
  309. * (populate, etc.)
  310. */
  311. function _next(ctx, cb) {
  312. let callback = cb;
  313. if (ctx._transforms.length) {
  314. callback = function(err, doc) {
  315. if (err || (doc === null && !ctx._mongooseOptions.transformNull)) {
  316. return cb(err, doc);
  317. }
  318. cb(err, ctx._transforms.reduce(function(doc, fn) {
  319. return fn.call(ctx, doc);
  320. }, doc));
  321. };
  322. }
  323. if (ctx._error) {
  324. return immediate(function() {
  325. callback(ctx._error);
  326. });
  327. }
  328. if (ctx.cursor) {
  329. if (ctx.query._mongooseOptions.populate && !ctx._pop) {
  330. ctx._pop = helpers.preparePopulationOptionsMQ(ctx.query,
  331. ctx.query._mongooseOptions);
  332. ctx._pop.__noPromise = true;
  333. }
  334. if (ctx.query._mongooseOptions.populate && ctx.options._populateBatchSize > 1) {
  335. if (ctx._batchDocs && ctx._batchDocs.length) {
  336. // Return a cached populated doc
  337. return _nextDoc(ctx, ctx._batchDocs.shift(), ctx._pop, callback);
  338. } else if (ctx._batchExhausted) {
  339. // Internal cursor reported no more docs. Act the same here
  340. return callback(null, null);
  341. } else {
  342. // Request as many docs as batchSize, to populate them also in batch
  343. ctx._batchDocs = [];
  344. return ctx.cursor.next(_onNext.bind({ ctx, callback }));
  345. }
  346. } else {
  347. return ctx.cursor.next(function(error, doc) {
  348. if (error) {
  349. return callback(error);
  350. }
  351. if (!doc) {
  352. return callback(null, null);
  353. }
  354. if (!ctx.query._mongooseOptions.populate) {
  355. return _nextDoc(ctx, doc, null, callback);
  356. }
  357. ctx.query.model.populate(doc, ctx._pop, function(err, doc) {
  358. if (err) {
  359. return callback(err);
  360. }
  361. return _nextDoc(ctx, doc, ctx._pop, callback);
  362. });
  363. });
  364. }
  365. } else {
  366. ctx.once('error', cb);
  367. ctx.once('cursor', function(cursor) {
  368. ctx.removeListener('error', cb);
  369. if (cursor == null) {
  370. return;
  371. }
  372. _next(ctx, cb);
  373. });
  374. }
  375. }
  376. /*!
  377. * ignore
  378. */
  379. function _onNext(error, doc) {
  380. if (error) {
  381. return this.callback(error);
  382. }
  383. if (!doc) {
  384. this.ctx._batchExhausted = true;
  385. return _populateBatch.call(this);
  386. }
  387. this.ctx._batchDocs.push(doc);
  388. if (this.ctx._batchDocs.length < this.ctx.options._populateBatchSize) {
  389. // If both `batchSize` and `_populateBatchSize` are huge, calling `next()` repeatedly may
  390. // cause a stack overflow. So make sure we clear the stack regularly.
  391. if (this.ctx._batchDocs.length > 0 && this.ctx._batchDocs.length % 1000 === 0) {
  392. return immediate(() => this.ctx.cursor.next(_onNext.bind(this)));
  393. }
  394. this.ctx.cursor.next(_onNext.bind(this));
  395. } else {
  396. _populateBatch.call(this);
  397. }
  398. }
  399. /*!
  400. * ignore
  401. */
  402. function _populateBatch() {
  403. if (!this.ctx._batchDocs.length) {
  404. return this.callback(null, null);
  405. }
  406. const _this = this;
  407. this.ctx.query.model.populate(this.ctx._batchDocs, this.ctx._pop, function(err) {
  408. if (err) {
  409. return _this.callback(err);
  410. }
  411. _nextDoc(_this.ctx, _this.ctx._batchDocs.shift(), _this.ctx._pop, _this.callback);
  412. });
  413. }
  414. /*!
  415. * ignore
  416. */
  417. function _nextDoc(ctx, doc, pop, callback) {
  418. if (ctx.query._mongooseOptions.lean) {
  419. return ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => {
  420. if (err != null) {
  421. return callback(err);
  422. }
  423. callback(null, doc);
  424. });
  425. }
  426. const { model, _fields, _userProvidedFields, options } = ctx.query;
  427. helpers.createModelAndInit(model, doc, _fields, _userProvidedFields, options, pop, (err, doc) => {
  428. if (err != null) {
  429. return callback(err);
  430. }
  431. ctx.model.hooks.execPost('find', ctx.query, [[doc]], err => {
  432. if (err != null) {
  433. return callback(err);
  434. }
  435. callback(null, doc);
  436. });
  437. });
  438. }
  439. /*!
  440. * ignore
  441. */
  442. function _waitForCursor(ctx, cb) {
  443. if (ctx.cursor) {
  444. return cb();
  445. }
  446. ctx.once('cursor', function(cursor) {
  447. if (cursor == null) {
  448. return;
  449. }
  450. cb();
  451. });
  452. }
  453. module.exports = QueryCursor;