QueryCursor.js 12 KB

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