PageRenderTime 52ms CodeModel.GetById 40ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 1ms

/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
  5var Readable = require('stream').Readable;
  6var eachAsync = require('../services/cursor/eachAsync');
  7var helpers = require('../queryhelpers');
  8var util = require('util');
  9var utils = require('../utils');
 10
 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, but **not** the model's
 18 * post find hooks.
 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
 33function QueryCursor(query, options) {
 34  Readable.call(this, { objectMode: true });
 35
 36  this.cursor = null;
 37  this.query = query;
 38  this._transforms = options.transform ? [options.transform] : [];
 39  var _this = this;
 40  var model = query.model;
 41  model.hooks.execPre('find', query, function() {
 42    model.collection.find(query._conditions, options, function(err, cursor) {
 43      if (_this._error) {
 44        cursor.close(function() {});
 45        _this.listeners('error').length > 0 && _this.emit('error', _this._error);
 46      }
 47      if (err) {
 48        return _this.emit('error', err);
 49      }
 50      _this.cursor = cursor;
 51      _this.emit('cursor', cursor);
 52    });
 53  });
 54}
 55
 56util.inherits(QueryCursor, Readable);
 57
 58/*!
 59 * Necessary to satisfy the Readable API
 60 */
 61
 62QueryCursor.prototype._read = function() {
 63  var _this = this;
 64  _next(this, function(error, doc) {
 65    if (error) {
 66      return _this.emit('error', error);
 67    }
 68    if (!doc) {
 69      _this.push(null);
 70      _this.cursor.close(function(error) {
 71        if (error) {
 72          return _this.emit('error', error);
 73        }
 74        setTimeout(function() {
 75          _this.emit('close');
 76        }, 0);
 77      });
 78      return;
 79    }
 80    _this.push(doc);
 81  });
 82};
 83
 84/**
 85 * Registers a transform function which subsequently maps documents retrieved
 86 * via the streams interface or `.next()`
 87 *
 88 * ####Example
 89 *
 90 *     // Map documents returned by `data` events
 91 *     Thing.
 92 *       find({ name: /^hello/ }).
 93 *       cursor().
 94 *       map(function (doc) {
 95 *        doc.foo = "bar";
 96 *        return doc;
 97 *       })
 98 *       on('data', function(doc) { console.log(doc.foo); });
 99 *
100 *     // Or map documents returned by `.next()`
101 *     var cursor = Thing.find({ name: /^hello/ }).
102 *       cursor().
103 *       map(function (doc) {
104 *         doc.foo = "bar";
105 *         return doc;
106 *       });
107 *     cursor.next(function(error, doc) {
108 *       console.log(doc.foo);
109 *     });
110 *
111 * @param {Function} fn
112 * @return {QueryCursor}
113 * @api public
114 * @method map
115 */
116
117QueryCursor.prototype.map = function(fn) {
118  this._transforms.push(fn);
119  return this;
120};
121
122/*!
123 * Marks this cursor as errored
124 */
125
126QueryCursor.prototype._markError = function(error) {
127  this._error = error;
128  return this;
129};
130
131/**
132 * Marks this cursor as closed. Will stop streaming and subsequent calls to
133 * `next()` will error.
134 *
135 * @param {Function} callback
136 * @return {Promise}
137 * @api public
138 * @method close
139 * @emits close
140 * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close
141 */
142
143QueryCursor.prototype.close = function(callback) {
144  return utils.promiseOrCallback(callback, cb => {
145    this.cursor.close(error => {
146      if (error) {
147        cb(error);
148        return this.listeners('error').length > 0 && this.emit('error', error);
149      }
150      this.emit('close');
151      cb(null);
152    });
153  });
154};
155
156/**
157 * Get the next document from this cursor. Will return `null` when there are
158 * no documents left.
159 *
160 * @param {Function} callback
161 * @return {Promise}
162 * @api public
163 * @method next
164 */
165
166QueryCursor.prototype.next = function(callback) {
167  return utils.promiseOrCallback(callback, cb => {
168    _next(this, function(error, doc) {
169      if (error) {
170        return cb(error);
171      }
172      cb(null, doc);
173    });
174  });
175};
176
177/**
178 * Execute `fn` for every document in the cursor. If `fn` returns a promise,
179 * will wait for the promise to resolve before iterating on to the next one.
180 * Returns a promise that resolves when done.
181 *
182 * @param {Function} fn
183 * @param {Object} [options]
184 * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1.
185 * @param {Function} [callback] executed when all docs have been processed
186 * @return {Promise}
187 * @api public
188 * @method eachAsync
189 */
190
191QueryCursor.prototype.eachAsync = function(fn, opts, callback) {
192  var _this = this;
193  if (typeof opts === 'function') {
194    callback = opts;
195    opts = {};
196  }
197  opts = opts || {};
198
199  return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback);
200};
201
202/**
203 * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag).
204 * Useful for setting the `noCursorTimeout` and `tailable` flags.
205 *
206 * @param {String} flag
207 * @param {Boolean} value
208 * @return {AggregationCursor} this
209 * @api public
210 * @method addCursorFlag
211 */
212
213QueryCursor.prototype.addCursorFlag = function(flag, value) {
214  var _this = this;
215  _waitForCursor(this, function() {
216    _this.cursor.addCursorFlag(flag, value);
217  });
218  return this;
219};
220
221/*!
222 * Get the next doc from the underlying cursor and mongooseify it
223 * (populate, etc.)
224 */
225
226function _next(ctx, cb) {
227  var callback = cb;
228  if (ctx._transforms.length) {
229    callback = function(err, doc) {
230      if (err || doc === null) {
231        return cb(err, doc);
232      }
233      cb(err, ctx._transforms.reduce(function(doc, fn) {
234        return fn(doc);
235      }, doc));
236    };
237  }
238
239  if (ctx._error) {
240    return process.nextTick(function() {
241      callback(ctx._error);
242    });
243  }
244
245  if (ctx.cursor) {
246    return ctx.cursor.next(function(error, doc) {
247      if (error) {
248        return callback(error);
249      }
250      if (!doc) {
251        return callback(null, null);
252      }
253
254      var opts = ctx.query._mongooseOptions;
255      if (!opts.populate) {
256        return opts.lean === true ?
257          callback(null, doc) :
258          _create(ctx, doc, null, callback);
259      }
260
261      var pop = helpers.preparePopulationOptionsMQ(ctx.query,
262        ctx.query._mongooseOptions);
263      pop.__noPromise = true;
264      ctx.query.model.populate(doc, pop, function(err, doc) {
265        if (err) {
266          return callback(err);
267        }
268        return opts.lean === true ?
269          callback(null, doc) :
270          _create(ctx, doc, pop, callback);
271      });
272    });
273  } else {
274    ctx.once('cursor', function() {
275      _next(ctx, cb);
276    });
277  }
278}
279
280/*!
281 * ignore
282 */
283
284function _waitForCursor(ctx, cb) {
285  if (ctx.cursor) {
286    return cb();
287  }
288  ctx.once('cursor', function() {
289    cb();
290  });
291}
292
293/*!
294 * Convert a raw doc into a full mongoose doc.
295 */
296
297function _create(ctx, doc, populatedIds, cb) {
298  var instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields);
299  var opts = populatedIds ?
300    { populated: populatedIds } :
301    undefined;
302
303  instance.init(doc, opts, function(err) {
304    if (err) {
305      return cb(err);
306    }
307    cb(null, instance);
308  });
309}
310
311module.exports = QueryCursor;