/node_modules/mongoose/lib/cursor/QueryCursor.js

https://bitbucket.org/coleman333/smartsite · JavaScript · 311 lines · 164 code · 32 blank · 115 comment · 23 complexity · 3329c1bf0bf07c6c0a8c42da74328f9d MD5 · raw file

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