Source: lib/cursor.js

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