cursor.js 22 KB

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