You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

262 lines
6.4 KiB

  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()`](/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. var _this = this;
  31. var model = query.model;
  32. model.collection.find(query._conditions, options, function(err, cursor) {
  33. if (_this._error) {
  34. cursor.close(function() {});
  35. _this.listeners('error').length > 0 && _this.emit('error', _this._error);
  36. }
  37. if (err) {
  38. return _this.emit('error', err);
  39. }
  40. _this.cursor = cursor;
  41. _this.emit('cursor', cursor);
  42. });
  43. }
  44. util.inherits(QueryCursor, Readable);
  45. /*!
  46. * Necessary to satisfy the Readable API
  47. */
  48. QueryCursor.prototype._read = function() {
  49. var _this = this;
  50. _next(this, function(error, doc) {
  51. if (error) {
  52. return _this.emit('error', error);
  53. }
  54. if (!doc) {
  55. _this.push(null);
  56. return _this.cursor.close(function(error) {
  57. if (error) {
  58. return _this.emit('error', error);
  59. }
  60. _this.emit('close');
  61. });
  62. }
  63. _this.push(doc);
  64. });
  65. };
  66. /*!
  67. * Marks this cursor as errored
  68. */
  69. QueryCursor.prototype._markError = function(error) {
  70. this._error = error;
  71. return this;
  72. };
  73. /**
  74. * Marks this cursor as closed. Will stop streaming and subsequent calls to
  75. * `next()` will error.
  76. *
  77. * @param {Function} callback
  78. * @return {Promise}
  79. * @api public
  80. * @method close
  81. * @emits close
  82. * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
  83. */
  84. QueryCursor.prototype.close = function(callback) {
  85. var Promise = PromiseProvider.get();
  86. var _this = this;
  87. return new Promise.ES6(function(resolve, reject) {
  88. _this.cursor.close(function(error) {
  89. if (error) {
  90. callback && callback(error);
  91. reject(error);
  92. return _this.listeners('error').length > 0 &&
  93. _this.emit('error', error);
  94. }
  95. _this.emit('close');
  96. resolve();
  97. callback && callback();
  98. });
  99. });
  100. };
  101. /**
  102. * Get the next document from this cursor. Will return `null` when there are
  103. * no documents left.
  104. *
  105. * @param {Function} callback
  106. * @return {Promise}
  107. * @api public
  108. * @method next
  109. */
  110. QueryCursor.prototype.next = function(callback) {
  111. var Promise = PromiseProvider.get();
  112. var _this = this;
  113. return new Promise.ES6(function(resolve, reject) {
  114. _next(_this, function(error, doc) {
  115. if (error) {
  116. callback && callback(error);
  117. return reject(error);
  118. }
  119. callback && callback(null, doc);
  120. resolve(doc);
  121. });
  122. });
  123. };
  124. /**
  125. * Execute `fn` for every document in the cursor. If `fn` returns a promise,
  126. * will wait for the promise to resolve before iterating on to the next one.
  127. * Returns a promise that resolves when done.
  128. *
  129. * @param {Function} fn
  130. * @param {Function} [callback] executed when all docs have been processed
  131. * @return {Promise}
  132. * @api public
  133. * @method eachAsync
  134. */
  135. QueryCursor.prototype.eachAsync = function(fn, callback) {
  136. var Promise = PromiseProvider.get();
  137. var _this = this;
  138. var handleNextResult = function(doc, callback) {
  139. var promise = fn(doc);
  140. if (promise && typeof promise.then === 'function') {
  141. promise.then(
  142. function() { callback(null); },
  143. function(error) { callback(error); });
  144. } else {
  145. callback(null);
  146. }
  147. };
  148. var iterate = function(callback) {
  149. return _next(_this, function(error, doc) {
  150. if (error) {
  151. return callback(error);
  152. }
  153. if (!doc) {
  154. return callback(null);
  155. }
  156. handleNextResult(doc, function(error) {
  157. if (error) {
  158. return callback(error);
  159. }
  160. iterate(callback);
  161. });
  162. });
  163. };
  164. return new Promise.ES6(function(resolve, reject) {
  165. iterate(function(error) {
  166. if (error) {
  167. callback && callback(error);
  168. return reject(error);
  169. }
  170. callback && callback(null);
  171. return resolve();
  172. });
  173. });
  174. };
  175. /*!
  176. * Get the next doc from the underlying cursor and mongooseify it
  177. * (populate, etc.)
  178. */
  179. function _next(ctx, callback) {
  180. if (ctx._error) {
  181. return process.nextTick(function() {
  182. callback(ctx._error);
  183. });
  184. }
  185. if (ctx.cursor) {
  186. ctx.cursor.next(function(error, doc) {
  187. if (error) {
  188. return callback(error);
  189. }
  190. if (!doc) {
  191. return callback(null, null);
  192. }
  193. var opts = ctx.query._mongooseOptions;
  194. if (!opts.populate) {
  195. return opts.lean === true ?
  196. callback(null, doc) :
  197. _create(ctx, doc, null, callback);
  198. }
  199. var pop = helpers.preparePopulationOptionsMQ(ctx.query,
  200. ctx.query._mongooseOptions);
  201. pop.forEach(function(option) {
  202. delete option.model;
  203. });
  204. pop.__noPromise = true;
  205. ctx.query.model.populate(doc, pop, function(err, doc) {
  206. if (err) {
  207. return callback(err);
  208. }
  209. return opts.lean === true ?
  210. callback(null, doc) :
  211. _create(ctx, doc, pop, callback);
  212. });
  213. });
  214. } else {
  215. ctx.once('cursor', function() {
  216. _next(ctx, callback);
  217. });
  218. }
  219. }
  220. /*!
  221. * Convert a raw doc into a full mongoose doc.
  222. */
  223. function _create(ctx, doc, populatedIds, cb) {
  224. var instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields);
  225. var opts = populatedIds ?
  226. { populated: populatedIds } :
  227. undefined;
  228. instance.init(doc, opts, function(err) {
  229. if (err) {
  230. return cb(err);
  231. }
  232. cb(null, instance);
  233. });
  234. }
  235. module.exports = QueryCursor;