Ohm-Management - Projektarbeit B-ME
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.

cursor.js 22KB

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