Source: lib/cursor.js

  1. "use strict";
  2. var inherits = require('util').inherits
  3. , f = require('util').format
  4. , formattedOrderClause = require('./utils').formattedOrderClause
  5. , handleCallback = require('./utils').handleCallback
  6. , ReadPreference = require('./read_preference')
  7. , MongoError = require('mongodb-core').MongoError
  8. , Readable = require('stream').Readable || require('readable-stream').Readable
  9. , Define = require('./metadata')
  10. , CoreCursor = require('mongodb-core').Cursor
  11. , Map = require('mongodb-core').BSON.Map
  12. , CoreReadPreference = require('mongodb-core').ReadPreference;
  13. /**
  14. * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
  15. * allowing for iteration over the results returned from the underlying query. It supports
  16. * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
  17. * or higher stream
  18. *
  19. * **CURSORS Cannot directly be instantiated**
  20. * @example
  21. * var MongoClient = require('mongodb').MongoClient,
  22. * test = require('assert');
  23. * // Connection url
  24. * var url = 'mongodb://localhost:27017/test';
  25. * // Connect using MongoClient
  26. * MongoClient.connect(url, function(err, db) {
  27. * // Create a collection we want to drop later
  28. * var col = db.collection('createIndexExample1');
  29. * // Insert a bunch of documents
  30. * col.insert([{a:1, b:1}
  31. * , {a:2, b:2}, {a:3, b:3}
  32. * , {a:4, b:4}], {w:1}, function(err, result) {
  33. * test.equal(null, err);
  34. *
  35. * // Show that duplicate records got dropped
  36. * col.find({}).toArray(function(err, items) {
  37. * test.equal(null, err);
  38. * test.equal(4, items.length);
  39. * db.close();
  40. * });
  41. * });
  42. * });
  43. */
  44. /**
  45. * Namespace provided by the mongodb-core and node.js
  46. * @external CoreCursor
  47. * @external Readable
  48. */
  49. // Flags allowed for cursor
  50. var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];
  51. var fields = ['numberOfRetries', 'tailableRetryInterval'];
  52. var push = Array.prototype.push;
  53. /**
  54. * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)
  55. * @class Cursor
  56. * @extends external:CoreCursor
  57. * @extends external:Readable
  58. * @property {string} sortValue Cursor query sort setting.
  59. * @property {boolean} timeout Is Cursor able to time out.
  60. * @property {ReadPreference} readPreference Get cursor ReadPreference.
  61. * @fires Cursor#data
  62. * @fires Cursor#end
  63. * @fires Cursor#close
  64. * @fires Cursor#readable
  65. * @return {Cursor} a Cursor instance.
  66. * @example
  67. * Cursor cursor options.
  68. *
  69. * collection.find({}).project({a:1}) // Create a projection of field a
  70. * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10
  71. * collection.find({}).batchSize(5) // Set batchSize on cursor to 5
  72. * collection.find({}).filter({a:1}) // Set query on the cursor
  73. * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries
  74. * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable
  75. * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay
  76. * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout
  77. * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData
  78. * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial
  79. * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1}
  80. * collection.find({}).max(10) // Set the cursor maxScan
  81. * collection.find({}).maxScan(10) // Set the cursor maxScan
  82. * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS
  83. * collection.find({}).min(100) // Set the cursor min
  84. * collection.find({}).returnKey(10) // Set the cursor returnKey
  85. * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference
  86. * collection.find({}).showRecordId(true) // Set the cursor showRecordId
  87. * collection.find({}).snapshot(true) // Set the cursor snapshot
  88. * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query
  89. * collection.find({}).hint('a_1') // Set the cursor hint
  90. *
  91. * All options are chainable, so one can do the following.
  92. *
  93. * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..)
  94. */
  95. var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
  96. CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
  97. var self = this;
  98. var state = Cursor.INIT;
  99. var streamOptions = {};
  100. // Tailable cursor options
  101. var numberOfRetries = options.numberOfRetries || 5;
  102. var tailableRetryInterval = options.tailableRetryInterval || 500;
  103. var currentNumberOfRetries = numberOfRetries;
  104. // Get the promiseLibrary
  105. var promiseLibrary = options.promiseLibrary;
  106. // No promise library selected fall back
  107. if(!promiseLibrary) {
  108. promiseLibrary = typeof global.Promise == 'function' ?
  109. global.Promise : require('es6-promise').Promise;
  110. }
  111. // Set up
  112. Readable.call(this, {objectMode: true});
  113. // Internal cursor state
  114. this.s = {
  115. // Tailable cursor options
  116. numberOfRetries: numberOfRetries
  117. , tailableRetryInterval: tailableRetryInterval
  118. , currentNumberOfRetries: currentNumberOfRetries
  119. // State
  120. , state: state
  121. // Stream options
  122. , streamOptions: streamOptions
  123. // BSON
  124. , bson: bson
  125. // Namespace
  126. , ns: ns
  127. // Command
  128. , cmd: cmd
  129. // Options
  130. , options: options
  131. // Topology
  132. , topology: topology
  133. // Topology options
  134. , topologyOptions: topologyOptions
  135. // Promise library
  136. , promiseLibrary: promiseLibrary
  137. // Current doc
  138. , currentDoc: null
  139. }
  140. // Translate correctly
  141. if(self.s.options.noCursorTimeout == true) {
  142. self.addCursorFlag('noCursorTimeout', true);
  143. }
  144. // Set the sort value
  145. this.sortValue = self.s.cmd.sort;
  146. // Get the batchSize
  147. var batchSize = cmd.cursor && cmd.cursor.batchSize
  148. ? cmd.cursor && cmd.cursor.batchSize
  149. : (options.cursor && options.cursor.batchSize ? options.cursor.batchSize : 1000);
  150. // Set the batchSize
  151. this.setCursorBatchSize(batchSize);
  152. }
  153. /**
  154. * Cursor stream data event, fired for each document in the cursor.
  155. *
  156. * @event Cursor#data
  157. * @type {object}
  158. */
  159. /**
  160. * Cursor stream end event
  161. *
  162. * @event Cursor#end
  163. * @type {null}
  164. */
  165. /**
  166. * Cursor stream close event
  167. *
  168. * @event Cursor#close
  169. * @type {null}
  170. */
  171. /**
  172. * Cursor stream readable event
  173. *
  174. * @event Cursor#readable
  175. * @type {null}
  176. */
  177. // Inherit from Readable
  178. inherits(Cursor, Readable);
  179. // Map core cursor _next method so we can apply mapping
  180. CoreCursor.prototype._next = CoreCursor.prototype.next;
  181. for(var name in CoreCursor.prototype) {
  182. Cursor.prototype[name] = CoreCursor.prototype[name];
  183. }
  184. var define = Cursor.define = new Define('Cursor', Cursor, true);
  185. /**
  186. * Check if there is any document still available in the cursor
  187. * @method
  188. * @param {Cursor~resultCallback} [callback] The result callback.
  189. * @throws {MongoError}
  190. * @return {Promise} returns Promise if no callback passed
  191. */
  192. Cursor.prototype.hasNext = function(callback) {
  193. var self = this;
  194. // Execute using callback
  195. if(typeof callback == 'function') {
  196. if(self.s.currentDoc){
  197. return callback(null, true);
  198. } else {
  199. return nextObject(self, function(err, doc) {
  200. if (err) return callback(err, null);
  201. if (!doc) return callback(null, false);
  202. self.s.currentDoc = doc;
  203. callback(null, true);
  204. });
  205. }
  206. }
  207. // Return a Promise
  208. return new this.s.promiseLibrary(function(resolve, reject) {
  209. if(self.s.currentDoc){
  210. resolve(true);
  211. } else {
  212. nextObject(self, function(err, doc) {
  213. if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false);
  214. if(err) return reject(err);
  215. if(!doc) return resolve(false);
  216. self.s.currentDoc = doc;
  217. resolve(true);
  218. });
  219. }
  220. });
  221. }
  222. define.classMethod('hasNext', {callback: true, promise:true});
  223. /**
  224. * Get the next available document from the cursor, returns null if no more documents are available.
  225. * @method
  226. * @param {Cursor~resultCallback} [callback] The result callback.
  227. * @throws {MongoError}
  228. * @return {Promise} returns Promise if no callback passed
  229. */
  230. Cursor.prototype.next = function(callback) {
  231. var self = this;
  232. // Execute using callback
  233. if(typeof callback == 'function') {
  234. // Return the currentDoc if someone called hasNext first
  235. if(self.s.currentDoc) {
  236. var doc = self.s.currentDoc;
  237. self.s.currentDoc = null;
  238. return callback(null, doc);
  239. }
  240. // Return the next object
  241. return nextObject(self, callback)
  242. }
  243. // Return a Promise
  244. return new this.s.promiseLibrary(function(resolve, reject) {
  245. // Return the currentDoc if someone called hasNext first
  246. if(self.s.currentDoc) {
  247. var doc = self.s.currentDoc;
  248. self.s.currentDoc = null;
  249. return resolve(doc);
  250. }
  251. nextObject(self, function(err, r) {
  252. if(err) return reject(err);
  253. resolve(r);
  254. });
  255. });
  256. }
  257. define.classMethod('next', {callback: true, promise:true});
  258. /**
  259. * Set the cursor query
  260. * @method
  261. * @param {object} filter The filter object used for the cursor.
  262. * @return {Cursor}
  263. */
  264. Cursor.prototype.filter = function(filter) {
  265. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  266. this.s.cmd.query = filter;
  267. return this;
  268. }
  269. define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]});
  270. /**
  271. * Set the cursor maxScan
  272. * @method
  273. * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query
  274. * @return {Cursor}
  275. */
  276. Cursor.prototype.maxScan = function(maxScan) {
  277. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  278. this.s.cmd.maxScan = maxScan;
  279. return this;
  280. }
  281. define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]});
  282. /**
  283. * Set the cursor hint
  284. * @method
  285. * @param {object} hint If specified, then the query system will only consider plans using the hinted index.
  286. * @return {Cursor}
  287. */
  288. Cursor.prototype.hint = function(hint) {
  289. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  290. this.s.cmd.hint = hint;
  291. return this;
  292. }
  293. define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]});
  294. /**
  295. * Set the cursor min
  296. * @method
  297. * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
  298. * @return {Cursor}
  299. */
  300. Cursor.prototype.min = function(min) {
  301. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  302. this.s.cmd.min = min;
  303. return this;
  304. }
  305. define.classMethod('min', {callback: false, promise:false, returns: [Cursor]});
  306. /**
  307. * Set the cursor max
  308. * @method
  309. * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
  310. * @return {Cursor}
  311. */
  312. Cursor.prototype.max = function(max) {
  313. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  314. this.s.cmd.max = max;
  315. return this;
  316. }
  317. define.classMethod('max', {callback: false, promise:false, returns: [Cursor]});
  318. /**
  319. * Set the cursor returnKey
  320. * @method
  321. * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms:
  322. * @return {Cursor}
  323. */
  324. Cursor.prototype.returnKey = function(value) {
  325. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  326. this.s.cmd.returnKey = value;
  327. return this;
  328. }
  329. define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]});
  330. /**
  331. * Set the cursor showRecordId
  332. * @method
  333. * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
  334. * @return {Cursor}
  335. */
  336. Cursor.prototype.showRecordId = function(value) {
  337. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  338. this.s.cmd.showDiskLoc = value;
  339. return this;
  340. }
  341. define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]});
  342. /**
  343. * Set the cursor snapshot
  344. * @method
  345. * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.
  346. * @return {Cursor}
  347. */
  348. Cursor.prototype.snapshot = function(value) {
  349. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  350. this.s.cmd.snapshot = value;
  351. return this;
  352. }
  353. define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]});
  354. /**
  355. * Set a node.js specific cursor option
  356. * @method
  357. * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].
  358. * @param {object} value The field value.
  359. * @throws {MongoError}
  360. * @return {Cursor}
  361. */
  362. Cursor.prototype.setCursorOption = function(field, value) {
  363. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  364. if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true });
  365. this.s[field] = value;
  366. if(field == 'numberOfRetries')
  367. this.s.currentNumberOfRetries = value;
  368. return this;
  369. }
  370. define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]});
  371. /**
  372. * Add a cursor flag to the cursor
  373. * @method
  374. * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].
  375. * @param {boolean} value The flag boolean value.
  376. * @throws {MongoError}
  377. * @return {Cursor}
  378. */
  379. Cursor.prototype.addCursorFlag = function(flag, value) {
  380. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  381. if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true });
  382. if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true});
  383. this.s.cmd[flag] = value;
  384. return this;
  385. }
  386. define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]});
  387. /**
  388. * Add a query modifier to the cursor query
  389. * @method
  390. * @param {string} name The query modifier (must start with $, such as $orderby etc)
  391. * @param {boolean} value The flag boolean value.
  392. * @throws {MongoError}
  393. * @return {Cursor}
  394. */
  395. Cursor.prototype.addQueryModifier = function(name, value) {
  396. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  397. if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true});
  398. // Strip of the $
  399. var field = name.substr(1);
  400. // Set on the command
  401. this.s.cmd[field] = value;
  402. // Deal with the special case for sort
  403. if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field];
  404. return this;
  405. }
  406. define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]});
  407. /**
  408. * Add a comment to the cursor query allowing for tracking the comment in the log.
  409. * @method
  410. * @param {string} value The comment attached to this query.
  411. * @throws {MongoError}
  412. * @return {Cursor}
  413. */
  414. Cursor.prototype.comment = function(value) {
  415. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  416. this.s.cmd.comment = value;
  417. return this;
  418. }
  419. define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]});
  420. /**
  421. * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
  422. * @method
  423. * @param {number} value Number of milliseconds to wait before aborting the tailed query.
  424. * @throws {MongoError}
  425. * @return {Cursor}
  426. */
  427. Cursor.prototype.maxAwaitTimeMS = function(value) {
  428. if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true});
  429. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  430. this.s.cmd.maxAwaitTimeMS = value;
  431. return this;
  432. }
  433. define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]});
  434. /**
  435. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  436. * @method
  437. * @param {number} value Number of milliseconds to wait before aborting the query.
  438. * @throws {MongoError}
  439. * @return {Cursor}
  440. */
  441. Cursor.prototype.maxTimeMS = function(value) {
  442. if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true});
  443. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  444. this.s.cmd.maxTimeMS = value;
  445. return this;
  446. }
  447. define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]});
  448. Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;
  449. define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]});
  450. /**
  451. * Sets a field projection for the query.
  452. * @method
  453. * @param {object} value The field projection object.
  454. * @throws {MongoError}
  455. * @return {Cursor}
  456. */
  457. Cursor.prototype.project = function(value) {
  458. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  459. this.s.cmd.fields = value;
  460. return this;
  461. }
  462. define.classMethod('project', {callback: false, promise:false, returns: [Cursor]});
  463. /**
  464. * Sets the sort order of the cursor query.
  465. * @method
  466. * @param {(string|array|object)} keyOrList The key or keys set for the sort.
  467. * @param {number} [direction] The direction of the sorting (1 or -1).
  468. * @throws {MongoError}
  469. * @return {Cursor}
  470. */
  471. Cursor.prototype.sort = function(keyOrList, direction) {
  472. if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true});
  473. if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  474. var order = keyOrList;
  475. // We have an array of arrays, we need to preserve the order of the sort
  476. // so we will us a Map
  477. if(Array.isArray(order) && Array.isArray(order[0])) {
  478. order = new Map(order.map(function(x) {
  479. var value = [x[0], null];
  480. if(x[1] == 'asc') {
  481. value[1] = 1;
  482. } else if(x[1] == 'desc') {
  483. value[1] = -1;
  484. } else if(x[1] == 1 || x[1] == -1) {
  485. value[1] = x[1];
  486. } else {
  487. throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
  488. }
  489. return value;
  490. }));
  491. }
  492. if(direction != null) {
  493. order = [[keyOrList, direction]];
  494. }
  495. this.s.cmd.sort = order;
  496. this.sortValue = order;
  497. return this;
  498. }
  499. define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]});
  500. /**
  501. * Set the batch size for the cursor.
  502. * @method
  503. * @param {number} value The batchSize for the cursor.
  504. * @throws {MongoError}
  505. * @return {Cursor}
  506. */
  507. Cursor.prototype.batchSize = function(value) {
  508. if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true});
  509. if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  510. if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
  511. this.s.cmd.batchSize = value;
  512. this.setCursorBatchSize(value);
  513. return this;
  514. }
  515. define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]});
  516. /**
  517. * Set the collation options for the cursor.
  518. * @method
  519. * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  520. * @throws {MongoError}
  521. * @return {Cursor}
  522. */
  523. Cursor.prototype.collation = function(value) {
  524. this.s.cmd.collation = value;
  525. return this;
  526. }
  527. define.classMethod('collation', {callback: false, promise:false, returns: [Cursor]});
  528. /**
  529. * Set the limit for the cursor.
  530. * @method
  531. * @param {number} value The limit for the cursor query.
  532. * @throws {MongoError}
  533. * @return {Cursor}
  534. */
  535. Cursor.prototype.limit = function(value) {
  536. if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true});
  537. if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  538. if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true});
  539. this.s.cmd.limit = value;
  540. // this.cursorLimit = value;
  541. this.setCursorLimit(value);
  542. return this;
  543. }
  544. define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]});
  545. /**
  546. * Set the skip for the cursor.
  547. * @method
  548. * @param {number} value The skip for the cursor query.
  549. * @throws {MongoError}
  550. * @return {Cursor}
  551. */
  552. Cursor.prototype.skip = function(value) {
  553. if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true});
  554. if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  555. if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true});
  556. this.s.cmd.skip = value;
  557. this.setCursorSkip(value);
  558. return this;
  559. }
  560. define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]});
  561. /**
  562. * The callback format for results
  563. * @callback Cursor~resultCallback
  564. * @param {MongoError} error An error instance representing the error during the execution.
  565. * @param {(object|null|boolean)} result The result object if the command was executed successfully.
  566. */
  567. /**
  568. * Clone the cursor
  569. * @function external:CoreCursor#clone
  570. * @return {Cursor}
  571. */
  572. /**
  573. * Resets the cursor
  574. * @function external:CoreCursor#rewind
  575. * @return {null}
  576. */
  577. /**
  578. * Get the next available document from the cursor, returns null if no more documents are available.
  579. * @method
  580. * @param {Cursor~resultCallback} [callback] The result callback.
  581. * @throws {MongoError}
  582. * @deprecated
  583. * @return {Promise} returns Promise if no callback passed
  584. */
  585. Cursor.prototype.nextObject = Cursor.prototype.next;
  586. var nextObject = function(self, callback) {
  587. if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
  588. if(self.s.state == Cursor.INIT && self.s.cmd.sort) {
  589. try {
  590. self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort);
  591. } catch(err) {
  592. return handleCallback(callback, err);
  593. }
  594. }
  595. // Get the next object
  596. self._next(function(err, doc) {
  597. self.s.state = Cursor.OPEN;
  598. if(err) return handleCallback(callback, err);
  599. handleCallback(callback, null, doc);
  600. });
  601. }
  602. define.classMethod('nextObject', {callback: true, promise:true});
  603. // Trampoline emptying the number of retrieved items
  604. // without incurring a nextTick operation
  605. var loop = function(self, callback) {
  606. // No more items we are done
  607. if(self.bufferedCount() == 0) return;
  608. // Get the next document
  609. self._next(callback);
  610. // Loop
  611. return loop;
  612. }
  613. Cursor.prototype.next = Cursor.prototype.nextObject;
  614. define.classMethod('next', {callback: true, promise:true});
  615. /**
  616. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  617. * not all of the elements will be iterated if this cursor had been previously accessed.
  618. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  619. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  620. * at any given time if batch size is specified. Otherwise, the caller is responsible
  621. * for making sure that the entire result can fit the memory.
  622. * @method
  623. * @deprecated
  624. * @param {Cursor~resultCallback} callback The result callback.
  625. * @throws {MongoError}
  626. * @return {null}
  627. */
  628. Cursor.prototype.each = function(callback) {
  629. // Rewind cursor state
  630. this.rewind();
  631. // Set current cursor to INIT
  632. this.s.state = Cursor.INIT;
  633. // Run the query
  634. _each(this, callback);
  635. };
  636. define.classMethod('each', {callback: true, promise:false});
  637. // Run the each loop
  638. var _each = function(self, callback) {
  639. if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true});
  640. if(self.isNotified()) return;
  641. if(self.s.state == Cursor.CLOSED || self.isDead()) {
  642. return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
  643. }
  644. if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN;
  645. // Define function to avoid global scope escape
  646. var fn = null;
  647. // Trampoline all the entries
  648. if(self.bufferedCount() > 0) {
  649. while(fn = loop(self, callback)) fn(self, callback);
  650. _each(self, callback);
  651. } else {
  652. self.next(function(err, item) {
  653. if(err) return handleCallback(callback, err);
  654. if(item == null) {
  655. self.s.state = Cursor.CLOSED;
  656. return handleCallback(callback, null, null);
  657. }
  658. if(handleCallback(callback, null, item) == false) return;
  659. _each(self, callback);
  660. })
  661. }
  662. }
  663. /**
  664. * The callback format for the forEach iterator method
  665. * @callback Cursor~iteratorCallback
  666. * @param {Object} doc An emitted document for the iterator
  667. */
  668. /**
  669. * The callback error format for the forEach iterator method
  670. * @callback Cursor~endCallback
  671. * @param {MongoError} error An error instance representing the error during the execution.
  672. */
  673. /**
  674. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  675. * @method
  676. * @param {Cursor~iteratorCallback} iterator The iteration callback.
  677. * @param {Cursor~endCallback} callback The end callback.
  678. * @throws {MongoError}
  679. * @return {null}
  680. */
  681. Cursor.prototype.forEach = function(iterator, callback) {
  682. this.each(function(err, doc){
  683. if(err) { callback(err); return false; }
  684. if(doc != null) { iterator(doc); return true; }
  685. if(doc == null && callback) {
  686. var internalCallback = callback;
  687. callback = null;
  688. internalCallback(null);
  689. return false;
  690. }
  691. });
  692. }
  693. define.classMethod('forEach', {callback: true, promise:false});
  694. /**
  695. * Set the ReadPreference for the cursor.
  696. * @method
  697. * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
  698. * @throws {MongoError}
  699. * @return {Cursor}
  700. */
  701. Cursor.prototype.setReadPreference = function(r) {
  702. if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
  703. if(r instanceof ReadPreference) {
  704. this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  705. } else if(typeof r == 'string'){
  706. this.s.options.readPreference = new CoreReadPreference(r);
  707. } else if(r instanceof CoreReadPreference) {
  708. this.s.options.readPreference = r;
  709. }
  710. return this;
  711. }
  712. define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]});
  713. /**
  714. * The callback format for results
  715. * @callback Cursor~toArrayResultCallback
  716. * @param {MongoError} error An error instance representing the error during the execution.
  717. * @param {object[]} documents All the documents the satisfy the cursor.
  718. */
  719. /**
  720. * Returns an array of documents. The caller is responsible for making sure that there
  721. * is enough memory to store the results. Note that the array only contain partial
  722. * results when this cursor had been previously accessed. In that case,
  723. * cursor.rewind() can be used to reset the cursor.
  724. * @method
  725. * @param {Cursor~toArrayResultCallback} [callback] The result callback.
  726. * @throws {MongoError}
  727. * @return {Promise} returns Promise if no callback passed
  728. */
  729. Cursor.prototype.toArray = function(callback) {
  730. var self = this;
  731. if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true});
  732. // Execute using callback
  733. if(typeof callback == 'function') return toArray(self, callback);
  734. // Return a Promise
  735. return new this.s.promiseLibrary(function(resolve, reject) {
  736. toArray(self, function(err, r) {
  737. if(err) return reject(err);
  738. resolve(r);
  739. });
  740. });
  741. }
  742. var toArray = function(self, callback) {
  743. var items = [];
  744. // Reset cursor
  745. self.rewind();
  746. self.s.state = Cursor.INIT;
  747. // Fetch all the documents
  748. var fetchDocs = function() {
  749. self._next(function(err, doc) {
  750. if(err) return handleCallback(callback, err);
  751. if(doc == null) {
  752. self.s.state = Cursor.CLOSED;
  753. return handleCallback(callback, null, items);
  754. }
  755. // Add doc to items
  756. items.push(doc)
  757. // Get all buffered objects
  758. if(self.bufferedCount() > 0) {
  759. var docs = self.readBufferedDocuments(self.bufferedCount())
  760. // Transform the doc if transform method added
  761. if(self.s.transforms && typeof self.s.transforms.doc == 'function') {
  762. docs = docs.map(self.s.transforms.doc);
  763. }
  764. push.apply(items, docs);
  765. }
  766. // Attempt a fetch
  767. fetchDocs();
  768. })
  769. }
  770. fetchDocs();
  771. }
  772. define.classMethod('toArray', {callback: true, promise:true});
  773. /**
  774. * The callback format for results
  775. * @callback Cursor~countResultCallback
  776. * @param {MongoError} error An error instance representing the error during the execution.
  777. * @param {number} count The count of documents.
  778. */
  779. /**
  780. * Get the count of documents for this cursor
  781. * @method
  782. * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options.
  783. * @param {object} [options=null] Optional settings.
  784. * @param {number} [options.skip=null] The number of documents to skip.
  785. * @param {number} [options.limit=null] The maximum amounts to count before aborting.
  786. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  787. * @param {string} [options.hint=null] An index name hint for the query.
  788. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  789. * @param {Cursor~countResultCallback} [callback] The result callback.
  790. * @return {Promise} returns Promise if no callback passed
  791. */
  792. Cursor.prototype.count = function(applySkipLimit, opts, callback) {
  793. var self = this;
  794. if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true});
  795. if(typeof opts == 'function') callback = opts, opts = {};
  796. opts = opts || {};
  797. // Execute using callback
  798. if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback);
  799. // Return a Promise
  800. return new this.s.promiseLibrary(function(resolve, reject) {
  801. count(self, applySkipLimit, opts, function(err, r) {
  802. if(err) return reject(err);
  803. resolve(r);
  804. });
  805. });
  806. };
  807. var count = function(self, applySkipLimit, opts, callback) {
  808. if(typeof applySkipLimit == 'function') {
  809. callback = applySkipLimit;
  810. applySkipLimit = true;
  811. }
  812. if(applySkipLimit) {
  813. if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip();
  814. if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit();
  815. }
  816. // Command
  817. var delimiter = self.s.ns.indexOf('.');
  818. var command = {
  819. 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query
  820. }
  821. // Apply a readConcern if set
  822. if(self.s.cmd.readConcern) {
  823. command.readConcern = self.s.cmd.readConcern;
  824. }
  825. // Apply a hint if set
  826. if(self.s.cmd.hint) {
  827. command.hint = self.s.cmd.hint;
  828. }
  829. if(typeof opts.maxTimeMS == 'number') {
  830. command.maxTimeMS = opts.maxTimeMS;
  831. } else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') {
  832. command.maxTimeMS = self.s.cmd.maxTimeMS;
  833. }
  834. // Merge in any options
  835. if(opts.skip) command.skip = opts.skip;
  836. if(opts.limit) command.limit = opts.limit;
  837. if(self.s.options.hint) command.hint = self.s.options.hint;
  838. // Set cursor server to the same as the topology
  839. self.server = self.topology;
  840. // Execute the command
  841. self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter))
  842. , command, function(err, result) {
  843. callback(err, result ? result.result.n : null)
  844. }, self.options);
  845. }
  846. define.classMethod('count', {callback: true, promise:true});
  847. /**
  848. * Close the cursor, sending a KillCursor command and emitting close.
  849. * @method
  850. * @param {Cursor~resultCallback} [callback] The result callback.
  851. * @return {Promise} returns Promise if no callback passed
  852. */
  853. Cursor.prototype.close = function(callback) {
  854. this.s.state = Cursor.CLOSED;
  855. // Kill the cursor
  856. this.kill();
  857. // Emit the close event for the cursor
  858. this.emit('close');
  859. // Callback if provided
  860. if(typeof callback == 'function') return handleCallback(callback, null, this);
  861. // Return a Promise
  862. return new this.s.promiseLibrary(function(resolve) {
  863. resolve();
  864. });
  865. }
  866. define.classMethod('close', {callback: true, promise:true});
  867. /**
  868. * Map all documents using the provided function
  869. * @method
  870. * @param {function} [transform] The mapping transformation method.
  871. * @return {Cursor}
  872. */
  873. Cursor.prototype.map = function(transform) {
  874. if(this.cursorState.transforms && this.cursorState.transforms.doc) {
  875. var oldTransform = this.cursorState.transforms.doc;
  876. this.cursorState.transforms.doc = function (doc) { return transform(oldTransform(doc)); };
  877. } else {
  878. this.cursorState.transforms = { doc: transform };
  879. }
  880. return this;
  881. }
  882. define.classMethod('map', {callback: false, promise:false, returns: [Cursor]});
  883. /**
  884. * Is the cursor closed
  885. * @method
  886. * @return {boolean}
  887. */
  888. Cursor.prototype.isClosed = function() {
  889. return this.isDead();
  890. }
  891. define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
  892. Cursor.prototype.destroy = function(err) {
  893. if(err) this.emit('error', err);
  894. this.pause();
  895. this.close();
  896. }
  897. define.classMethod('destroy', {callback: false, promise:false});
  898. /**
  899. * Return a modified Readable stream including a possible transform method.
  900. * @method
  901. * @param {object} [options=null] Optional settings.
  902. * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream.
  903. * @return {Cursor}
  904. */
  905. Cursor.prototype.stream = function(options) {
  906. this.s.streamOptions = options || {};
  907. return this;
  908. }
  909. define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]});
  910. /**
  911. * Execute the explain for the cursor
  912. * @method
  913. * @param {Cursor~resultCallback} [callback] The result callback.
  914. * @return {Promise} returns Promise if no callback passed
  915. */
  916. Cursor.prototype.explain = function(callback) {
  917. var self = this;
  918. this.s.cmd.explain = true;
  919. // Do we have a readConcern
  920. if(this.s.cmd.readConcern) {
  921. delete this.s.cmd['readConcern'];
  922. }
  923. // Execute using callback
  924. if(typeof callback == 'function') return this._next(callback);
  925. // Return a Promise
  926. return new this.s.promiseLibrary(function(resolve, reject) {
  927. self._next(function(err, r) {
  928. if(err) return reject(err);
  929. resolve(r);
  930. });
  931. });
  932. }
  933. define.classMethod('explain', {callback: true, promise:true});
  934. Cursor.prototype._read = function() {
  935. var self = this;
  936. if(self.s.state == Cursor.CLOSED || self.isDead()) {
  937. return self.push(null);
  938. }
  939. // Get the next item
  940. self.nextObject(function(err, result) {
  941. if(err) {
  942. if(self.listeners('error') && self.listeners('error').length > 0) {
  943. self.emit('error', err);
  944. }
  945. if(!self.isDead()) self.close();
  946. // Emit end event
  947. self.emit('end');
  948. return self.emit('finish');
  949. }
  950. // If we provided a transformation method
  951. if(typeof self.s.streamOptions.transform == 'function' && result != null) {
  952. return self.push(self.s.streamOptions.transform(result));
  953. }
  954. // If we provided a map function
  955. if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) {
  956. return self.push(self.cursorState.transforms.doc(result));
  957. }
  958. // Return the result
  959. self.push(result);
  960. });
  961. }
  962. Object.defineProperty(Cursor.prototype, 'readPreference', {
  963. enumerable:true,
  964. get: function() {
  965. if (!this || !this.s) {
  966. return null;
  967. }
  968. return this.s.options.readPreference;
  969. }
  970. });
  971. Object.defineProperty(Cursor.prototype, 'namespace', {
  972. enumerable: true,
  973. get: function() {
  974. if (!this || !this.s) {
  975. return null;
  976. }
  977. // TODO: refactor this logic into core
  978. var ns = this.s.ns || '';
  979. var firstDot = ns.indexOf('.');
  980. if (firstDot < 0) {
  981. return {
  982. database: this.s.ns,
  983. collection: ''
  984. };
  985. }
  986. return {
  987. database: ns.substr(0, firstDot),
  988. collection: ns.substr(firstDot + 1)
  989. };
  990. }
  991. });
  992. /**
  993. * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
  994. * @function external:Readable#read
  995. * @param {number} size Optional argument to specify how much data to read.
  996. * @return {(String | Buffer | null)}
  997. */
  998. /**
  999. * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
  1000. * @function external:Readable#setEncoding
  1001. * @param {string} encoding The encoding to use.
  1002. * @return {null}
  1003. */
  1004. /**
  1005. * This method will cause the readable stream to resume emitting data events.
  1006. * @function external:Readable#resume
  1007. * @return {null}
  1008. */
  1009. /**
  1010. * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
  1011. * @function external:Readable#pause
  1012. * @return {null}
  1013. */
  1014. /**
  1015. * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
  1016. * @function external:Readable#pipe
  1017. * @param {Writable} destination The destination for writing data
  1018. * @param {object} [options] Pipe options
  1019. * @return {null}
  1020. */
  1021. /**
  1022. * This method will remove the hooks set up for a previous pipe() call.
  1023. * @function external:Readable#unpipe
  1024. * @param {Writable} [destination] The destination for writing data
  1025. * @return {null}
  1026. */
  1027. /**
  1028. * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
  1029. * @function external:Readable#unshift
  1030. * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
  1031. * @return {null}
  1032. */
  1033. /**
  1034. * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
  1035. * @function external:Readable#wrap
  1036. * @param {Stream} stream An "old style" readable stream.
  1037. * @return {null}
  1038. */
  1039. Cursor.INIT = 0;
  1040. Cursor.OPEN = 1;
  1041. Cursor.CLOSED = 2;
  1042. Cursor.GET_MORE = 3;
  1043. module.exports = Cursor;