cursor.js 36 KB

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