cursor.js 35 KB

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