PageRenderTime 77ms CodeModel.GetById 12ms app.highlight 58ms RepoModel.GetById 2ms app.codeStats 0ms

/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js

https://bitbucket.org/coleman333/smartsite
JavaScript | 794 lines | 476 code | 103 blank | 215 comment | 112 complexity | 24a4f12c8dbf74a5b559dcd38d73b376 MD5 | raw file
  1'use strict';
  2
  3var Logger = require('./connection/logger'),
  4  retrieveBSON = require('./connection/utils').retrieveBSON,
  5  MongoError = require('./error').MongoError,
  6  MongoNetworkError = require('./error').MongoNetworkError,
  7  f = require('util').format;
  8
  9var BSON = retrieveBSON(),
 10  Long = BSON.Long;
 11
 12/**
 13 * This is a cursor results callback
 14 *
 15 * @callback resultCallback
 16 * @param {error} error An error object. Set to null if no error present
 17 * @param {object} document
 18 */
 19
 20/**
 21 * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
 22 * allowing for iteration over the results returned from the underlying query.
 23 *
 24 * **CURSORS Cannot directly be instantiated**
 25 * @example
 26 * var Server = require('mongodb-core').Server
 27 *   , ReadPreference = require('mongodb-core').ReadPreference
 28 *   , assert = require('assert');
 29 *
 30 * var server = new Server({host: 'localhost', port: 27017});
 31 * // Wait for the connection event
 32 * server.on('connect', function(server) {
 33 *   assert.equal(null, err);
 34 *
 35 *   // Execute the write
 36 *   var cursor = _server.cursor('integration_tests.inserts_example4', {
 37 *       find: 'integration_tests.example4'
 38 *     , query: {a:1}
 39 *   }, {
 40 *     readPreference: new ReadPreference('secondary');
 41 *   });
 42 *
 43 *   // Get the first document
 44 *   cursor.next(function(err, doc) {
 45 *     assert.equal(null, err);
 46 *     server.destroy();
 47 *   });
 48 * });
 49 *
 50 * // Start connecting
 51 * server.connect();
 52 */
 53
 54/**
 55 * Creates a new Cursor, not to be used directly
 56 * @class
 57 * @param {object} bson An instance of the BSON parser
 58 * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1)
 59 * @param {{object}|Long} cmd The selector (can be a command or a cursorId)
 60 * @param {object} [options=null] Optional settings.
 61 * @param {object} [options.batchSize=1000] Batchsize for the operation
 62 * @param {array} [options.documents=[]] Initial documents list for cursor
 63 * @param {object} [options.transforms=null] Transform methods for the cursor results
 64 * @param {function} [options.transforms.query] Transform the value returned from the initial query
 65 * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next
 66 * @param {object} topology The server topology instance.
 67 * @param {object} topologyOptions The server topology options.
 68 * @return {Cursor} A cursor instance
 69 * @property {number} cursorBatchSize The current cursorBatchSize for the cursor
 70 * @property {number} cursorLimit The current cursorLimit for the cursor
 71 * @property {number} cursorSkip The current cursorSkip for the cursor
 72 */
 73var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
 74  options = options || {};
 75
 76  // Cursor pool
 77  this.pool = null;
 78  // Cursor server
 79  this.server = null;
 80
 81  // Do we have a not connected handler
 82  this.disconnectHandler = options.disconnectHandler;
 83
 84  // Set local values
 85  this.bson = bson;
 86  this.ns = ns;
 87  this.cmd = cmd;
 88  this.options = options;
 89  this.topology = topology;
 90
 91  // All internal state
 92  this.cursorState = {
 93    cursorId: null,
 94    cmd: cmd,
 95    documents: options.documents || [],
 96    cursorIndex: 0,
 97    dead: false,
 98    killed: false,
 99    init: false,
100    notified: false,
101    limit: options.limit || cmd.limit || 0,
102    skip: options.skip || cmd.skip || 0,
103    batchSize: options.batchSize || cmd.batchSize || 1000,
104    currentLimit: 0,
105    // Result field name if not a cursor (contains the array of results)
106    transforms: options.transforms
107  };
108
109  // Add promoteLong to cursor state
110  if (typeof topologyOptions.promoteLongs === 'boolean') {
111    this.cursorState.promoteLongs = topologyOptions.promoteLongs;
112  } else if (typeof options.promoteLongs === 'boolean') {
113    this.cursorState.promoteLongs = options.promoteLongs;
114  } else if (typeof options.session === 'object') {
115    this.cursorState.session = options.session;
116  }
117
118  // Add promoteValues to cursor state
119  if (typeof topologyOptions.promoteValues === 'boolean') {
120    this.cursorState.promoteValues = topologyOptions.promoteValues;
121  } else if (typeof options.promoteValues === 'boolean') {
122    this.cursorState.promoteValues = options.promoteValues;
123  }
124
125  // Add promoteBuffers to cursor state
126  if (typeof topologyOptions.promoteBuffers === 'boolean') {
127    this.cursorState.promoteBuffers = topologyOptions.promoteBuffers;
128  } else if (typeof options.promoteBuffers === 'boolean') {
129    this.cursorState.promoteBuffers = options.promoteBuffers;
130  }
131
132  if (topologyOptions.reconnect) {
133    this.cursorState.reconnect = topologyOptions.reconnect;
134  }
135
136  // Logger
137  this.logger = Logger('Cursor', topologyOptions);
138
139  //
140  // Did we pass in a cursor id
141  if (typeof cmd === 'number') {
142    this.cursorState.cursorId = Long.fromNumber(cmd);
143    this.cursorState.lastCursorId = this.cursorState.cursorId;
144  } else if (cmd instanceof Long) {
145    this.cursorState.cursorId = cmd;
146    this.cursorState.lastCursorId = cmd;
147  }
148};
149
150Cursor.prototype.setCursorBatchSize = function(value) {
151  this.cursorState.batchSize = value;
152};
153
154Cursor.prototype.cursorBatchSize = function() {
155  return this.cursorState.batchSize;
156};
157
158Cursor.prototype.setCursorLimit = function(value) {
159  this.cursorState.limit = value;
160};
161
162Cursor.prototype.cursorLimit = function() {
163  return this.cursorState.limit;
164};
165
166Cursor.prototype.setCursorSkip = function(value) {
167  this.cursorState.skip = value;
168};
169
170Cursor.prototype.cursorSkip = function() {
171  return this.cursorState.skip;
172};
173
174//
175// Handle callback (including any exceptions thrown)
176var handleCallback = function(callback, err, result) {
177  try {
178    callback(err, result);
179  } catch (err) {
180    process.nextTick(function() {
181      throw err;
182    });
183  }
184};
185
186// Internal methods
187Cursor.prototype._find = function(callback) {
188  var self = this;
189
190  if (self.logger.isDebug()) {
191    self.logger.debug(
192      f(
193        'issue initial query [%s] with flags [%s]',
194        JSON.stringify(self.cmd),
195        JSON.stringify(self.query)
196      )
197    );
198  }
199
200  var queryCallback = function(err, r) {
201    if (err) return callback(err);
202
203    // Get the raw message
204    var result = r.message;
205
206    // Query failure bit set
207    if (result.queryFailure) {
208      return callback(new MongoError(result.documents[0]), null);
209    }
210
211    // Check if we have a command cursor
212    if (
213      Array.isArray(result.documents) &&
214      result.documents.length === 1 &&
215      (!self.cmd.find || (self.cmd.find && self.cmd.virtual === false)) &&
216      (result.documents[0].cursor !== 'string' ||
217        result.documents[0]['$err'] ||
218        result.documents[0]['errmsg'] ||
219        Array.isArray(result.documents[0].result))
220    ) {
221      // We have a an error document return the error
222      if (result.documents[0]['$err'] || result.documents[0]['errmsg']) {
223        return callback(new MongoError(result.documents[0]), null);
224      }
225
226      // We have a cursor document
227      if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') {
228        var id = result.documents[0].cursor.id;
229        // If we have a namespace change set the new namespace for getmores
230        if (result.documents[0].cursor.ns) {
231          self.ns = result.documents[0].cursor.ns;
232        }
233        // Promote id to long if needed
234        self.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id;
235        self.cursorState.lastCursorId = self.cursorState.cursorId;
236        // If we have a firstBatch set it
237        if (Array.isArray(result.documents[0].cursor.firstBatch)) {
238          self.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse();
239        }
240
241        // Return after processing command cursor
242        return callback(null, result);
243      }
244
245      if (Array.isArray(result.documents[0].result)) {
246        self.cursorState.documents = result.documents[0].result;
247        self.cursorState.cursorId = Long.ZERO;
248        return callback(null, result);
249      }
250    }
251
252    // Otherwise fall back to regular find path
253    self.cursorState.cursorId = result.cursorId;
254    self.cursorState.documents = result.documents;
255    self.cursorState.lastCursorId = result.cursorId;
256
257    // Transform the results with passed in transformation method if provided
258    if (self.cursorState.transforms && typeof self.cursorState.transforms.query === 'function') {
259      self.cursorState.documents = self.cursorState.transforms.query(result);
260    }
261
262    // Return callback
263    callback(null, result);
264  };
265
266  // Options passed to the pool
267  var queryOptions = {};
268
269  // If we have a raw query decorate the function
270  if (self.options.raw || self.cmd.raw) {
271    // queryCallback.raw = self.options.raw || self.cmd.raw;
272    queryOptions.raw = self.options.raw || self.cmd.raw;
273  }
274
275  // Do we have documentsReturnedIn set on the query
276  if (typeof self.query.documentsReturnedIn === 'string') {
277    // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn;
278    queryOptions.documentsReturnedIn = self.query.documentsReturnedIn;
279  }
280
281  // Add promote Long value if defined
282  if (typeof self.cursorState.promoteLongs === 'boolean') {
283    queryOptions.promoteLongs = self.cursorState.promoteLongs;
284  }
285
286  // Add promote values if defined
287  if (typeof self.cursorState.promoteValues === 'boolean') {
288    queryOptions.promoteValues = self.cursorState.promoteValues;
289  }
290
291  // Add promote values if defined
292  if (typeof self.cursorState.promoteBuffers === 'boolean') {
293    queryOptions.promoteBuffers = self.cursorState.promoteBuffers;
294  }
295
296  if (typeof self.cursorState.session === 'object') {
297    queryOptions.session = self.cursorState.session;
298  }
299
300  // Write the initial command out
301  self.server.s.pool.write(self.query, queryOptions, queryCallback);
302};
303
304Cursor.prototype._getmore = function(callback) {
305  if (this.logger.isDebug())
306    this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query)));
307  // Determine if it's a raw query
308  var raw = this.options.raw || this.cmd.raw;
309
310  // Set the current batchSize
311  var batchSize = this.cursorState.batchSize;
312  if (
313    this.cursorState.limit > 0 &&
314    this.cursorState.currentLimit + batchSize > this.cursorState.limit
315  ) {
316    batchSize = this.cursorState.limit - this.cursorState.currentLimit;
317  }
318
319  // Default pool
320  var pool = this.server.s.pool;
321
322  // We have a wire protocol handler
323  this.server.wireProtocolHandler.getMore(
324    this.bson,
325    this.ns,
326    this.cursorState,
327    batchSize,
328    raw,
329    pool,
330    this.options,
331    callback
332  );
333};
334
335Cursor.prototype._killcursor = function(callback) {
336  // Set cursor to dead
337  this.cursorState.dead = true;
338  this.cursorState.killed = true;
339  // Remove documents
340  this.cursorState.documents = [];
341
342  // If no cursor id just return
343  if (
344    this.cursorState.cursorId == null ||
345    this.cursorState.cursorId.isZero() ||
346    this.cursorState.init === false
347  ) {
348    if (callback) callback(null, null);
349    return;
350  }
351
352  // Default pool
353  var pool = this.server.s.pool;
354  // Execute command
355  this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState, pool, callback);
356};
357
358/**
359 * Clone the cursor
360 * @method
361 * @return {Cursor}
362 */
363Cursor.prototype.clone = function() {
364  return this.topology.cursor(this.ns, this.cmd, this.options);
365};
366
367/**
368 * Checks if the cursor is dead
369 * @method
370 * @return {boolean} A boolean signifying if the cursor is dead or not
371 */
372Cursor.prototype.isDead = function() {
373  return this.cursorState.dead === true;
374};
375
376/**
377 * Checks if the cursor was killed by the application
378 * @method
379 * @return {boolean} A boolean signifying if the cursor was killed by the application
380 */
381Cursor.prototype.isKilled = function() {
382  return this.cursorState.killed === true;
383};
384
385/**
386 * Checks if the cursor notified it's caller about it's death
387 * @method
388 * @return {boolean} A boolean signifying if the cursor notified the callback
389 */
390Cursor.prototype.isNotified = function() {
391  return this.cursorState.notified === true;
392};
393
394/**
395 * Returns current buffered documents length
396 * @method
397 * @return {number} The number of items in the buffered documents
398 */
399Cursor.prototype.bufferedCount = function() {
400  return this.cursorState.documents.length - this.cursorState.cursorIndex;
401};
402
403/**
404 * Returns current buffered documents
405 * @method
406 * @return {Array} An array of buffered documents
407 */
408Cursor.prototype.readBufferedDocuments = function(number) {
409  var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex;
410  var length = number < unreadDocumentsLength ? number : unreadDocumentsLength;
411  var elements = this.cursorState.documents.slice(
412    this.cursorState.cursorIndex,
413    this.cursorState.cursorIndex + length
414  );
415
416  // Transform the doc with passed in transformation method if provided
417  if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') {
418    // Transform all the elements
419    for (var i = 0; i < elements.length; i++) {
420      elements[i] = this.cursorState.transforms.doc(elements[i]);
421    }
422  }
423
424  // Ensure we do not return any more documents than the limit imposed
425  // Just return the number of elements up to the limit
426  if (
427    this.cursorState.limit > 0 &&
428    this.cursorState.currentLimit + elements.length > this.cursorState.limit
429  ) {
430    elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit);
431    this.kill();
432  }
433
434  // Adjust current limit
435  this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length;
436  this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length;
437
438  // Return elements
439  return elements;
440};
441
442/**
443 * Kill the cursor
444 * @method
445 * @param {resultCallback} callback A callback function
446 */
447Cursor.prototype.kill = function(callback) {
448  this._killcursor(callback);
449};
450
451/**
452 * Resets the cursor
453 * @method
454 * @return {null}
455 */
456Cursor.prototype.rewind = function() {
457  if (this.cursorState.init) {
458    if (!this.cursorState.dead) {
459      this.kill();
460    }
461
462    this.cursorState.currentLimit = 0;
463    this.cursorState.init = false;
464    this.cursorState.dead = false;
465    this.cursorState.killed = false;
466    this.cursorState.notified = false;
467    this.cursorState.documents = [];
468    this.cursorState.cursorId = null;
469    this.cursorState.cursorIndex = 0;
470  }
471};
472
473/**
474 * Validate if the pool is dead and return error
475 */
476var isConnectionDead = function(self, callback) {
477  if (self.pool && self.pool.isDestroyed()) {
478    self.cursorState.notified = true;
479    self.cursorState.killed = true;
480    self.cursorState.documents = [];
481    self.cursorState.cursorIndex = 0;
482    callback(
483      new MongoNetworkError(
484        f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port)
485      )
486    );
487    return true;
488  }
489
490  return false;
491};
492
493/**
494 * Validate if the cursor is dead but was not explicitly killed by user
495 */
496var isCursorDeadButNotkilled = function(self, callback) {
497  // Cursor is dead but not marked killed, return null
498  if (self.cursorState.dead && !self.cursorState.killed) {
499    self.cursorState.notified = true;
500    self.cursorState.killed = true;
501    self.cursorState.documents = [];
502    self.cursorState.cursorIndex = 0;
503    handleCallback(callback, null, null);
504    return true;
505  }
506
507  return false;
508};
509
510/**
511 * Validate if the cursor is dead and was killed by user
512 */
513var isCursorDeadAndKilled = function(self, callback) {
514  if (self.cursorState.dead && self.cursorState.killed) {
515    handleCallback(callback, new MongoError('cursor is dead'));
516    return true;
517  }
518
519  return false;
520};
521
522/**
523 * Validate if the cursor was killed by the user
524 */
525var isCursorKilled = function(self, callback) {
526  if (self.cursorState.killed) {
527    self.cursorState.notified = true;
528    self.cursorState.documents = [];
529    self.cursorState.cursorIndex = 0;
530    handleCallback(callback, null, null);
531    return true;
532  }
533
534  return false;
535};
536
537/**
538 * Mark cursor as being dead and notified
539 */
540var setCursorDeadAndNotified = function(self, callback) {
541  self.cursorState.dead = true;
542  self.cursorState.notified = true;
543  self.cursorState.documents = [];
544  self.cursorState.cursorIndex = 0;
545  handleCallback(callback, null, null);
546};
547
548/**
549 * Mark cursor as being notified
550 */
551var setCursorNotified = function(self, callback) {
552  self.cursorState.notified = true;
553  self.cursorState.documents = [];
554  self.cursorState.cursorIndex = 0;
555  handleCallback(callback, null, null);
556};
557
558var nextFunction = function(self, callback) {
559  // We have notified about it
560  if (self.cursorState.notified) {
561    return callback(new Error('cursor is exhausted'));
562  }
563
564  // Cursor is killed return null
565  if (isCursorKilled(self, callback)) return;
566
567  // Cursor is dead but not marked killed, return null
568  if (isCursorDeadButNotkilled(self, callback)) return;
569
570  // We have a dead and killed cursor, attempting to call next should error
571  if (isCursorDeadAndKilled(self, callback)) return;
572
573  // We have just started the cursor
574  if (!self.cursorState.init) {
575    // Topology is not connected, save the call in the provided store to be
576    // Executed at some point when the handler deems it's reconnected
577    if (!self.topology.isConnected(self.options)) {
578      // Only need this for single server, because repl sets and mongos
579      // will always continue trying to reconnect
580      if (self.topology._type === 'server' && !self.topology.s.options.reconnect) {
581        // Reconnect is disabled, so we'll never reconnect
582        return callback(new MongoError('no connection available'));
583      }
584
585      if (self.disconnectHandler != null) {
586        if (self.topology.isDestroyed()) {
587          // Topology was destroyed, so don't try to wait for it to reconnect
588          return callback(new MongoError('Topology was destroyed'));
589        }
590
591        return self.disconnectHandler.addObjectAndMethod(
592          'cursor',
593          self,
594          'next',
595          [callback],
596          callback
597        );
598      }
599    }
600
601    try {
602      self.server = self.topology.getServer(self.options);
603    } catch (err) {
604      // Handle the error and add object to next method call
605      if (self.disconnectHandler != null) {
606        return self.disconnectHandler.addObjectAndMethod(
607          'cursor',
608          self,
609          'next',
610          [callback],
611          callback
612        );
613      }
614
615      // Otherwise return the error
616      return callback(err);
617    }
618
619    // Set as init
620    self.cursorState.init = true;
621
622    // Server does not support server
623    if (self.cmd && self.cmd.collation && self.server.ismaster.maxWireVersion < 5) {
624      return callback(new MongoError(f('server %s does not support collation', self.server.name)));
625    }
626
627    try {
628      self.query = self.server.wireProtocolHandler.command(
629        self.bson,
630        self.ns,
631        self.cmd,
632        self.cursorState,
633        self.topology,
634        self.options
635      );
636    } catch (err) {
637      return callback(err);
638    }
639  }
640
641  // If we don't have a cursorId execute the first query
642  if (self.cursorState.cursorId == null) {
643    // Check if pool is dead and return if not possible to
644    // execute the query against the db
645    if (isConnectionDead(self, callback)) return;
646
647    // Check if topology is destroyed
648    if (self.topology.isDestroyed())
649      return callback(
650        new MongoNetworkError('connection destroyed, not possible to instantiate cursor')
651      );
652
653    // query, cmd, options, cursorState, callback
654    self._find(function(err) {
655      if (err) return handleCallback(callback, err, null);
656
657      if (
658        self.cursorState.documents.length === 0 &&
659        self.cursorState.cursorId &&
660        self.cursorState.cursorId.isZero() &&
661        !self.cmd.tailable &&
662        !self.cmd.awaitData
663      ) {
664        return setCursorNotified(self, callback);
665      }
666
667      nextFunction(self, callback);
668    });
669  } else if (
670    self.cursorState.limit > 0 &&
671    self.cursorState.currentLimit >= self.cursorState.limit
672  ) {
673    // Ensure we kill the cursor on the server
674    self.kill();
675    // Set cursor in dead and notified state
676    return setCursorDeadAndNotified(self, callback);
677  } else if (
678    self.cursorState.cursorIndex === self.cursorState.documents.length &&
679    !Long.ZERO.equals(self.cursorState.cursorId)
680  ) {
681    // Ensure an empty cursor state
682    self.cursorState.documents = [];
683    self.cursorState.cursorIndex = 0;
684
685    // Check if topology is destroyed
686    if (self.topology.isDestroyed())
687      return callback(
688        new MongoNetworkError('connection destroyed, not possible to instantiate cursor')
689      );
690
691    // Check if connection is dead and return if not possible to
692    // execute a getmore on this connection
693    if (isConnectionDead(self, callback)) return;
694
695    // Execute the next get more
696    self._getmore(function(err, doc, connection) {
697      if (err) return handleCallback(callback, err);
698
699      // Save the returned connection to ensure all getMore's fire over the same connection
700      self.connection = connection;
701
702      // Tailable cursor getMore result, notify owner about it
703      // No attempt is made here to retry, this is left to the user of the
704      // core module to handle to keep core simple
705      if (
706        self.cursorState.documents.length === 0 &&
707        self.cmd.tailable &&
708        Long.ZERO.equals(self.cursorState.cursorId)
709      ) {
710        // No more documents in the tailed cursor
711        return handleCallback(
712          callback,
713          new MongoError({
714            message: 'No more documents in tailed cursor',
715            tailable: self.cmd.tailable,
716            awaitData: self.cmd.awaitData
717          })
718        );
719      } else if (
720        self.cursorState.documents.length === 0 &&
721        self.cmd.tailable &&
722        !Long.ZERO.equals(self.cursorState.cursorId)
723      ) {
724        return nextFunction(self, callback);
725      }
726
727      if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
728        return setCursorDeadAndNotified(self, callback);
729      }
730
731      nextFunction(self, callback);
732    });
733  } else if (
734    self.cursorState.documents.length === self.cursorState.cursorIndex &&
735    self.cmd.tailable &&
736    Long.ZERO.equals(self.cursorState.cursorId)
737  ) {
738    return handleCallback(
739      callback,
740      new MongoError({
741        message: 'No more documents in tailed cursor',
742        tailable: self.cmd.tailable,
743        awaitData: self.cmd.awaitData
744      })
745    );
746  } else if (
747    self.cursorState.documents.length === self.cursorState.cursorIndex &&
748    Long.ZERO.equals(self.cursorState.cursorId)
749  ) {
750    setCursorDeadAndNotified(self, callback);
751  } else {
752    if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) {
753      // Ensure we kill the cursor on the server
754      self.kill();
755      // Set cursor in dead and notified state
756      return setCursorDeadAndNotified(self, callback);
757    }
758
759    // Increment the current cursor limit
760    self.cursorState.currentLimit += 1;
761
762    // Get the document
763    var doc = self.cursorState.documents[self.cursorState.cursorIndex++];
764
765    // Doc overflow
766    if (!doc || doc.$err) {
767      // Ensure we kill the cursor on the server
768      self.kill();
769      // Set cursor in dead and notified state
770      return setCursorDeadAndNotified(self, function() {
771        handleCallback(callback, new MongoError(doc ? doc.$err : undefined));
772      });
773    }
774
775    // Transform the doc with passed in transformation method if provided
776    if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') {
777      doc = self.cursorState.transforms.doc(doc);
778    }
779
780    // Return the document
781    handleCallback(callback, null, doc);
782  }
783};
784
785/**
786 * Retrieve the next document from the cursor
787 * @method
788 * @param {resultCallback} callback A callback function
789 */
790Cursor.prototype.next = function(callback) {
791  nextFunction(this, callback);
792};
793
794module.exports = Cursor;