querycursor.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*!
  2. * Module dependencies.
  3. */
  4. var PromiseProvider = require('./promise_provider');
  5. var Readable = require('stream').Readable;
  6. var helpers = require('./queryhelpers');
  7. var util = require('util');
  8. /**
  9. * A QueryCursor is a concurrency primitive for processing query results
  10. * one document at a time. A QueryCursor fulfills the [Node.js streams3 API](https://strongloop.com/strongblog/whats-new-io-js-beta-streams3/),
  11. * in addition to several other mechanisms for loading documents from MongoDB
  12. * one at a time.
  13. *
  14. * Unless you're an advanced user, do **not** instantiate this class directly.
  15. * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead.
  16. *
  17. * @param {Query} query
  18. * @param {Object} options query options passed to `.find()`
  19. * @inherits Readable
  20. * @event `cursor`: Emitted when the cursor is created
  21. * @event `error`: Emitted when an error occurred
  22. * @event `data`: Emitted when the stream is flowing and the next doc is ready
  23. * @event `end`: Emitted when the stream is exhausted
  24. * @api public
  25. */
  26. function QueryCursor(query, options) {
  27. Readable.call(this, { objectMode: true });
  28. this.cursor = null;
  29. this.query = query;
  30. this._transforms = options.transform ? [options.transform] : [];
  31. var _this = this;
  32. var model = query.model;
  33. model.collection.find(query._conditions, options, function(err, cursor) {
  34. if (_this._error) {
  35. cursor.close(function() {});
  36. _this.listeners('error').length > 0 && _this.emit('error', _this._error);
  37. }
  38. if (err) {
  39. return _this.emit('error', err);
  40. }
  41. _this.cursor = cursor;
  42. _this.emit('cursor', cursor);
  43. });
  44. }
  45. util.inherits(QueryCursor, Readable);
  46. /*!
  47. * Necessary to satisfy the Readable API
  48. */
  49. QueryCursor.prototype._read = function() {
  50. var _this = this;
  51. _next(this, function(error, doc) {
  52. if (error) {
  53. return _this.emit('error', error);
  54. }
  55. if (!doc) {
  56. _this.push(null);
  57. return _this.cursor.close(function(error) {
  58. if (error) {
  59. return _this.emit('error', error);
  60. }
  61. _this.emit('close');
  62. });
  63. }
  64. _this.push(doc);
  65. });
  66. };
  67. /**
  68. * Registers a transform function which subsequently maps documents retrieved
  69. * via the streams interface or `.next()`
  70. *
  71. * ####Example
  72. *
  73. * // Map documents returned by `data` events
  74. * Thing.
  75. * find({ name: /^hello/ }).
  76. * cursor().
  77. * map(function (doc) {
  78. * doc.foo = "bar";
  79. * return doc;
  80. * })
  81. * on('data', function(doc) { console.log(doc.foo); });
  82. *
  83. * // Or map documents returned by `.next()`
  84. * var cursor = Thing.find({ name: /^hello/ }).
  85. * cursor().
  86. * map(function (doc) {
  87. * doc.foo = "bar";
  88. * return doc;
  89. * });
  90. * cursor.next(function(error, doc) {
  91. * console.log(doc.foo);
  92. * });
  93. *
  94. * @param {Function} fn
  95. * @return {QueryCursor}
  96. * @api public
  97. * @method map
  98. */
  99. QueryCursor.prototype.map = function(fn) {
  100. this._transforms.push(fn);
  101. return this;
  102. };
  103. /*!
  104. * Marks this cursor as errored
  105. */
  106. QueryCursor.prototype._markError = function(error) {
  107. this._error = error;
  108. return this;
  109. };
  110. /**
  111. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  112. * `next()` will error.
  113. *
  114. * @param {Function} callback
  115. * @return {Promise}
  116. * @api public
  117. * @method close
  118. * @emits close
  119. * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
  120. */
  121. QueryCursor.prototype.close = function(callback) {
  122. var Promise = PromiseProvider.get();
  123. var _this = this;
  124. return new Promise.ES6(function(resolve, reject) {
  125. _this.cursor.close(function(error) {
  126. if (error) {
  127. callback && callback(error);
  128. reject(error);
  129. return _this.listeners('error').length > 0 &&
  130. _this.emit('error', error);
  131. }
  132. _this.emit('close');
  133. resolve();
  134. callback && callback();
  135. });
  136. });
  137. };
  138. /**
  139. * Get the next document from this cursor. Will return `null` when there are
  140. * no documents left.
  141. *
  142. * @param {Function} callback
  143. * @return {Promise}
  144. * @api public
  145. * @method next
  146. */
  147. QueryCursor.prototype.next = function(callback) {
  148. var Promise = PromiseProvider.get();
  149. var _this = this;
  150. return new Promise.ES6(function(resolve, reject) {
  151. _next(_this, function(error, doc) {
  152. if (error) {
  153. callback && callback(error);
  154. return reject(error);
  155. }
  156. callback && callback(null, doc);
  157. resolve(doc);
  158. });
  159. });
  160. };
  161. /**
  162. * Execute `fn` for every document in the cursor. If `fn` returns a promise,
  163. * will wait for the promise to resolve before iterating on to the next one.
  164. * Returns a promise that resolves when done.
  165. *
  166. * @param {Function} fn
  167. * @param {Function} [callback] executed when all docs have been processed
  168. * @return {Promise}
  169. * @api public
  170. * @method eachAsync
  171. */
  172. QueryCursor.prototype.eachAsync = function(fn, callback) {
  173. var Promise = PromiseProvider.get();
  174. var _this = this;
  175. var handleNextResult = function(doc, callback) {
  176. var promise = fn(doc);
  177. if (promise && typeof promise.then === 'function') {
  178. promise.then(
  179. function() { callback(null); },
  180. function(error) { callback(error); });
  181. } else {
  182. callback(null);
  183. }
  184. };
  185. var iterate = function(callback) {
  186. return _next(_this, function(error, doc) {
  187. if (error) {
  188. return callback(error);
  189. }
  190. if (!doc) {
  191. return callback(null);
  192. }
  193. handleNextResult(doc, function(error) {
  194. if (error) {
  195. return callback(error);
  196. }
  197. // Make sure to clear the stack re: gh-4697
  198. setTimeout(function() {
  199. iterate(callback);
  200. }, 0);
  201. });
  202. });
  203. };
  204. return new Promise.ES6(function(resolve, reject) {
  205. iterate(function(error) {
  206. if (error) {
  207. callback && callback(error);
  208. return reject(error);
  209. }
  210. callback && callback(null);
  211. return resolve();
  212. });
  213. });
  214. };
  215. /*!
  216. * Get the next doc from the underlying cursor and mongooseify it
  217. * (populate, etc.)
  218. */
  219. function _next(ctx, cb) {
  220. var callback = cb;
  221. if (ctx._transforms.length) {
  222. callback = function(err, doc) {
  223. if (err || doc === null) return cb(err, doc);
  224. cb(err, ctx._transforms.reduce(function(doc, fn) {
  225. return fn(doc);
  226. }, doc));
  227. };
  228. }
  229. if (ctx._error) {
  230. return process.nextTick(function() {
  231. callback(ctx._error);
  232. });
  233. }
  234. if (ctx.cursor) {
  235. ctx.cursor.next(function(error, doc) {
  236. if (error) {
  237. return callback(error);
  238. }
  239. if (!doc) {
  240. return callback(null, null);
  241. }
  242. var opts = ctx.query._mongooseOptions;
  243. if (!opts.populate) {
  244. return opts.lean === true ?
  245. callback(null, doc) :
  246. _create(ctx, doc, null, callback);
  247. }
  248. var pop = helpers.preparePopulationOptionsMQ(ctx.query,
  249. ctx.query._mongooseOptions);
  250. pop.forEach(function(option) {
  251. delete option.model;
  252. });
  253. pop.__noPromise = true;
  254. ctx.query.model.populate(doc, pop, function(err, doc) {
  255. if (err) {
  256. return callback(err);
  257. }
  258. return opts.lean === true ?
  259. callback(null, doc) :
  260. _create(ctx, doc, pop, callback);
  261. });
  262. });
  263. } else {
  264. ctx.once('cursor', function() {
  265. _next(ctx, callback);
  266. });
  267. }
  268. }
  269. /*!
  270. * Convert a raw doc into a full mongoose doc.
  271. */
  272. function _create(ctx, doc, populatedIds, cb) {
  273. var instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields);
  274. var opts = populatedIds ?
  275. { populated: populatedIds } :
  276. undefined;
  277. instance.init(doc, opts, function(err) {
  278. if (err) {
  279. return cb(err);
  280. }
  281. cb(null, instance);
  282. });
  283. }
  284. module.exports = QueryCursor;