cursor.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  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. set session(clientSession) {
  152. this.cursorState.session = clientSession;
  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. if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) {
  181. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  182. }
  183. return maybePromise(this, callback, cb => {
  184. const cursor = this;
  185. if (cursor.isNotified()) {
  186. return cb(null, false);
  187. }
  188. cursor._next((err, doc) => {
  189. if (err) return cb(err);
  190. if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) {
  191. return cb(null, false);
  192. }
  193. cursor.s.state = CursorState.OPEN;
  194. // NODE-2482: merge this into the core cursor implementation
  195. cursor.cursorState.cursorIndex--;
  196. if (cursor.cursorState.limit > 0) {
  197. cursor.cursorState.currentLimit--;
  198. }
  199. cb(null, true);
  200. });
  201. });
  202. }
  203. /**
  204. * Get the next available document from the cursor, returns null if no more documents are available.
  205. * @method
  206. * @param {Cursor~resultCallback} [callback] The result callback.
  207. * @throws {MongoError}
  208. * @return {Promise} returns Promise if no callback passed
  209. */
  210. next(callback) {
  211. return maybePromise(this, callback, cb => {
  212. const cursor = this;
  213. if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) {
  214. cb(MongoError.create({ message: 'Cursor is closed', driver: true }));
  215. return;
  216. }
  217. if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) {
  218. try {
  219. cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort);
  220. } catch (err) {
  221. return cb(err);
  222. }
  223. }
  224. cursor._next((err, doc) => {
  225. if (err) return cb(err);
  226. cursor.s.state = CursorState.OPEN;
  227. cb(null, doc);
  228. });
  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. filter(filter) {
  238. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  239. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  240. }
  241. this.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. maxScan(maxScan) {
  252. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  253. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  254. }
  255. this.cmd.maxScan = maxScan;
  256. return this;
  257. }
  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. hint(hint) {
  265. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  266. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  267. }
  268. this.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. min(min) {
  278. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  279. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  280. }
  281. this.cmd.min = min;
  282. return this;
  283. }
  284. /**
  285. * Set the cursor max
  286. * @method
  287. * @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.
  288. * @return {Cursor}
  289. */
  290. max(max) {
  291. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  292. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  293. }
  294. this.cmd.max = max;
  295. return this;
  296. }
  297. /**
  298. * 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.
  299. * @method
  300. * @param {bool} returnKey the returnKey value.
  301. * @return {Cursor}
  302. */
  303. returnKey(value) {
  304. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  305. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  306. }
  307. this.cmd.returnKey = value;
  308. return this;
  309. }
  310. /**
  311. * Set the cursor showRecordId
  312. * @method
  313. * @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.
  314. * @return {Cursor}
  315. */
  316. showRecordId(value) {
  317. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  318. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  319. }
  320. this.cmd.showDiskLoc = value;
  321. return this;
  322. }
  323. /**
  324. * Set the cursor snapshot
  325. * @method
  326. * @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.
  327. * @deprecated as of MongoDB 4.0
  328. * @return {Cursor}
  329. */
  330. snapshot(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. this.cmd.snapshot = value;
  335. return this;
  336. }
  337. /**
  338. * Set a node.js specific cursor option
  339. * @method
  340. * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].
  341. * @param {object} value The field value.
  342. * @throws {MongoError}
  343. * @return {Cursor}
  344. */
  345. setCursorOption(field, value) {
  346. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  347. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  348. }
  349. if (fields.indexOf(field) === -1) {
  350. throw MongoError.create({
  351. message: `option ${field} is not a supported option ${fields}`,
  352. driver: true
  353. });
  354. }
  355. this.s[field] = value;
  356. if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value;
  357. return this;
  358. }
  359. /**
  360. * Add a cursor flag to the cursor
  361. * @method
  362. * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].
  363. * @param {boolean} value The flag boolean value.
  364. * @throws {MongoError}
  365. * @return {Cursor}
  366. */
  367. addCursorFlag(flag, value) {
  368. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  369. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  370. }
  371. if (flags.indexOf(flag) === -1) {
  372. throw MongoError.create({
  373. message: `flag ${flag} is not a supported flag ${flags}`,
  374. driver: true
  375. });
  376. }
  377. if (typeof value !== 'boolean') {
  378. throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true });
  379. }
  380. this.cmd[flag] = value;
  381. return this;
  382. }
  383. /**
  384. * Add a query modifier to the cursor query
  385. * @method
  386. * @param {string} name The query modifier (must start with $, such as $orderby etc)
  387. * @param {string|boolean|number} value The modifier value.
  388. * @throws {MongoError}
  389. * @return {Cursor}
  390. */
  391. addQueryModifier(name, value) {
  392. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  393. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  394. }
  395. if (name[0] !== '$') {
  396. throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true });
  397. }
  398. // Strip of the $
  399. const field = name.substr(1);
  400. // Set on the command
  401. this.cmd[field] = value;
  402. // Deal with the special case for sort
  403. if (field === 'orderby') this.cmd.sort = this.cmd[field];
  404. return this;
  405. }
  406. /**
  407. * Add a comment to the cursor query allowing for tracking the comment in the log.
  408. * @method
  409. * @param {string} value The comment attached to this query.
  410. * @throws {MongoError}
  411. * @return {Cursor}
  412. */
  413. comment(value) {
  414. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  415. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  416. }
  417. this.cmd.comment = value;
  418. return this;
  419. }
  420. /**
  421. * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
  422. * @method
  423. * @param {number} value Number of milliseconds to wait before aborting the tailed query.
  424. * @throws {MongoError}
  425. * @return {Cursor}
  426. */
  427. maxAwaitTimeMS(value) {
  428. if (typeof value !== 'number') {
  429. throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true });
  430. }
  431. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  432. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  433. }
  434. this.cmd.maxAwaitTimeMS = value;
  435. return this;
  436. }
  437. /**
  438. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  439. * @method
  440. * @param {number} value Number of milliseconds to wait before aborting the query.
  441. * @throws {MongoError}
  442. * @return {Cursor}
  443. */
  444. maxTimeMS(value) {
  445. if (typeof value !== 'number') {
  446. throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true });
  447. }
  448. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  449. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  450. }
  451. this.cmd.maxTimeMS = value;
  452. return this;
  453. }
  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. project(value) {
  462. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) {
  463. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  464. }
  465. this.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. sort(keyOrList, direction) {
  477. if (this.options.tailable) {
  478. throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true });
  479. }
  480. if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.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.cmd.sort = order;
  509. return this;
  510. }
  511. /**
  512. * Set the batch size for the cursor.
  513. * @method
  514. * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}.
  515. * @throws {MongoError}
  516. * @return {Cursor}
  517. */
  518. batchSize(value) {
  519. if (this.options.tailable) {
  520. throw MongoError.create({
  521. message: "Tailable cursor doesn't support batchSize",
  522. driver: true
  523. });
  524. }
  525. if (this.s.state === CursorState.CLOSED || this.isDead()) {
  526. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  527. }
  528. if (typeof value !== 'number') {
  529. throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
  530. }
  531. this.cmd.batchSize = value;
  532. this.setCursorBatchSize(value);
  533. return this;
  534. }
  535. /**
  536. * Set the collation options for the cursor.
  537. * @method
  538. * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  539. * @throws {MongoError}
  540. * @return {Cursor}
  541. */
  542. collation(value) {
  543. this.cmd.collation = value;
  544. return this;
  545. }
  546. /**
  547. * Set the limit for the cursor.
  548. * @method
  549. * @param {number} value The limit for the cursor query.
  550. * @throws {MongoError}
  551. * @return {Cursor}
  552. */
  553. limit(value) {
  554. if (this.options.tailable) {
  555. throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true });
  556. }
  557. if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) {
  558. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  559. }
  560. if (typeof value !== 'number') {
  561. throw MongoError.create({ message: 'limit requires an integer', driver: true });
  562. }
  563. this.cmd.limit = value;
  564. this.setCursorLimit(value);
  565. return this;
  566. }
  567. /**
  568. * Set the skip for the cursor.
  569. * @method
  570. * @param {number} value The skip for the cursor query.
  571. * @throws {MongoError}
  572. * @return {Cursor}
  573. */
  574. skip(value) {
  575. if (this.options.tailable) {
  576. throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true });
  577. }
  578. if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) {
  579. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  580. }
  581. if (typeof value !== 'number') {
  582. throw MongoError.create({ message: 'skip requires an integer', driver: true });
  583. }
  584. this.cmd.skip = value;
  585. this.setCursorSkip(value);
  586. return this;
  587. }
  588. /**
  589. * The callback format for results
  590. * @callback Cursor~resultCallback
  591. * @param {MongoError} error An error instance representing the error during the execution.
  592. * @param {(object|null|boolean)} result The result object if the command was executed successfully.
  593. */
  594. /**
  595. * Clone the cursor
  596. * @function external:CoreCursor#clone
  597. * @return {Cursor}
  598. */
  599. /**
  600. * Resets the cursor
  601. * @function external:CoreCursor#rewind
  602. * @return {null}
  603. */
  604. /**
  605. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  606. * not all of the elements will be iterated if this cursor had been previously accessed.
  607. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  608. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  609. * at any given time if batch size is specified. Otherwise, the caller is responsible
  610. * for making sure that the entire result can fit the memory.
  611. * @method
  612. * @deprecated
  613. * @param {Cursor~resultCallback} callback The result callback.
  614. * @throws {MongoError}
  615. * @return {null}
  616. */
  617. each(callback) {
  618. // Rewind cursor state
  619. this.rewind();
  620. // Set current cursor to INIT
  621. this.s.state = CursorState.INIT;
  622. // Run the query
  623. each(this, callback);
  624. }
  625. /**
  626. * The callback format for the forEach iterator method
  627. * @callback Cursor~iteratorCallback
  628. * @param {Object} doc An emitted document for the iterator
  629. */
  630. /**
  631. * The callback error format for the forEach iterator method
  632. * @callback Cursor~endCallback
  633. * @param {MongoError} error An error instance representing the error during the execution.
  634. */
  635. /**
  636. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  637. * @method
  638. * @param {Cursor~iteratorCallback} iterator The iteration callback.
  639. * @param {Cursor~endCallback} callback The end callback.
  640. * @throws {MongoError}
  641. * @return {Promise} if no callback supplied
  642. */
  643. forEach(iterator, callback) {
  644. // Rewind cursor state
  645. this.rewind();
  646. // Set current cursor to INIT
  647. this.s.state = CursorState.INIT;
  648. if (typeof callback === 'function') {
  649. each(this, (err, doc) => {
  650. if (err) {
  651. callback(err);
  652. return false;
  653. }
  654. if (doc != null) {
  655. try {
  656. iterator(doc);
  657. } catch (error) {
  658. callback(error);
  659. return false;
  660. }
  661. return true;
  662. }
  663. if (doc == null && callback) {
  664. const internalCallback = callback;
  665. callback = null;
  666. internalCallback(null);
  667. return false;
  668. }
  669. });
  670. } else {
  671. return new this.s.promiseLibrary((fulfill, reject) => {
  672. each(this, (err, doc) => {
  673. if (err) {
  674. reject(err);
  675. return false;
  676. } else if (doc == null) {
  677. fulfill(null);
  678. return false;
  679. } else {
  680. try {
  681. iterator(doc);
  682. } catch (error) {
  683. reject(error);
  684. return false;
  685. }
  686. return true;
  687. }
  688. });
  689. });
  690. }
  691. }
  692. /**
  693. * Set the ReadPreference for the cursor.
  694. * @method
  695. * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
  696. * @throws {MongoError}
  697. * @return {Cursor}
  698. */
  699. setReadPreference(readPreference) {
  700. if (this.s.state !== CursorState.INIT) {
  701. throw MongoError.create({
  702. message: 'cannot change cursor readPreference after cursor has been accessed',
  703. driver: true
  704. });
  705. }
  706. if (readPreference instanceof ReadPreference) {
  707. this.options.readPreference = readPreference;
  708. } else if (typeof readPreference === 'string') {
  709. this.options.readPreference = new ReadPreference(readPreference);
  710. } else {
  711. throw new TypeError('Invalid read preference: ' + readPreference);
  712. }
  713. return this;
  714. }
  715. /**
  716. * The callback format for results
  717. * @callback Cursor~toArrayResultCallback
  718. * @param {MongoError} error An error instance representing the error during the execution.
  719. * @param {object[]} documents All the documents the satisfy the cursor.
  720. */
  721. /**
  722. * Returns an array of documents. The caller is responsible for making sure that there
  723. * is enough memory to store the results. Note that the array only contains partial
  724. * results when this cursor had been previously accessed. In that case,
  725. * cursor.rewind() can be used to reset the cursor.
  726. * @method
  727. * @param {Cursor~toArrayResultCallback} [callback] The result callback.
  728. * @throws {MongoError}
  729. * @return {Promise} returns Promise if no callback passed
  730. */
  731. toArray(callback) {
  732. if (this.options.tailable) {
  733. throw MongoError.create({
  734. message: 'Tailable cursor cannot be converted to array',
  735. driver: true
  736. });
  737. }
  738. return maybePromise(this, callback, cb => {
  739. const cursor = this;
  740. const items = [];
  741. // Reset cursor
  742. cursor.rewind();
  743. cursor.s.state = CursorState.INIT;
  744. // Fetch all the documents
  745. const fetchDocs = () => {
  746. cursor._next((err, doc) => {
  747. if (err) {
  748. return handleCallback(cb, err);
  749. }
  750. if (doc == null) {
  751. return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items));
  752. }
  753. // Add doc to items
  754. items.push(doc);
  755. // Get all buffered objects
  756. if (cursor.bufferedCount() > 0) {
  757. let docs = cursor.readBufferedDocuments(cursor.bufferedCount());
  758. Array.prototype.push.apply(items, docs);
  759. }
  760. // Attempt a fetch
  761. fetchDocs();
  762. });
  763. };
  764. fetchDocs();
  765. });
  766. }
  767. /**
  768. * The callback format for results
  769. * @callback Cursor~countResultCallback
  770. * @param {MongoError} error An error instance representing the error during the execution.
  771. * @param {number} count The count of documents.
  772. */
  773. /**
  774. * Get the count of documents for this cursor
  775. * @method
  776. * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options.
  777. * @param {object} [options] Optional settings.
  778. * @param {number} [options.skip] The number of documents to skip.
  779. * @param {number} [options.limit] The maximum amounts to count before aborting.
  780. * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query.
  781. * @param {string} [options.hint] An index name hint for the query.
  782. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  783. * @param {Cursor~countResultCallback} [callback] The result callback.
  784. * @return {Promise} returns Promise if no callback passed
  785. */
  786. count(applySkipLimit, opts, callback) {
  787. if (this.cmd.query == null)
  788. throw MongoError.create({
  789. message: 'count can only be used with find command',
  790. driver: true
  791. });
  792. if (typeof opts === 'function') (callback = opts), (opts = {});
  793. opts = opts || {};
  794. if (typeof applySkipLimit === 'function') {
  795. callback = applySkipLimit;
  796. applySkipLimit = true;
  797. }
  798. if (this.cursorState.session) {
  799. opts = Object.assign({}, opts, { session: this.cursorState.session });
  800. }
  801. const countOperation = new CountOperation(this, applySkipLimit, opts);
  802. return executeOperation(this.topology, countOperation, callback);
  803. }
  804. /**
  805. * Close the cursor, sending a KillCursor command and emitting close.
  806. * @method
  807. * @param {object} [options] Optional settings.
  808. * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor.
  809. * @param {Cursor~resultCallback} [callback] The result callback.
  810. * @return {Promise} returns Promise if no callback passed
  811. */
  812. close(options, callback) {
  813. if (typeof options === 'function') (callback = options), (options = {});
  814. options = Object.assign({}, { skipKillCursors: false }, options);
  815. return maybePromise(this, callback, cb => {
  816. this.s.state = CursorState.CLOSED;
  817. if (!options.skipKillCursors) {
  818. // Kill the cursor
  819. this.kill();
  820. }
  821. this._endSession(() => {
  822. this.emit('close');
  823. cb(null, this);
  824. });
  825. });
  826. }
  827. /**
  828. * Map all documents using the provided function
  829. * @method
  830. * @param {function} [transform] The mapping transformation method.
  831. * @return {Cursor}
  832. */
  833. map(transform) {
  834. if (this.cursorState.transforms && this.cursorState.transforms.doc) {
  835. const oldTransform = this.cursorState.transforms.doc;
  836. this.cursorState.transforms.doc = doc => {
  837. return transform(oldTransform(doc));
  838. };
  839. } else {
  840. this.cursorState.transforms = { doc: transform };
  841. }
  842. return this;
  843. }
  844. /**
  845. * Is the cursor closed
  846. * @method
  847. * @return {boolean}
  848. */
  849. isClosed() {
  850. return this.isDead();
  851. }
  852. destroy(err) {
  853. if (err) this.emit('error', err);
  854. this.pause();
  855. this.close();
  856. }
  857. /**
  858. * Return a modified Readable stream including a possible transform method.
  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 {Cursor}
  863. * TODO: replace this method with transformStream in next major release
  864. */
  865. stream(options) {
  866. this.cursorState.streamOptions = options || {};
  867. return this;
  868. }
  869. /**
  870. * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied,
  871. * returns a stream of unmodified docs.
  872. * @method
  873. * @param {object} [options] Optional settings.
  874. * @param {function} [options.transform] A transformation method applied to each document emitted by the stream.
  875. * @return {stream}
  876. */
  877. transformStream(options) {
  878. const streamOptions = options || {};
  879. if (typeof streamOptions.transform === 'function') {
  880. const stream = new Transform({
  881. objectMode: true,
  882. transform: function(chunk, encoding, callback) {
  883. this.push(streamOptions.transform(chunk));
  884. callback();
  885. }
  886. });
  887. return this.pipe(stream);
  888. }
  889. return this.pipe(new PassThrough({ objectMode: true }));
  890. }
  891. /**
  892. * Execute the explain for the cursor
  893. *
  894. * For backwards compatibility, a verbosity of true is interpreted as "allPlansExecution"
  895. * and false as "queryPlanner". Prior to server version 3.6, aggregate()
  896. * ignores the verbosity parameter and executes in "queryPlanner".
  897. *
  898. * @method
  899. * @param {'queryPlanner'|'queryPlannerExtended'|'executionStats'|'allPlansExecution'|boolean} [verbosity=true] - An optional mode in which to run the explain.
  900. * @param {Cursor~resultCallback} [callback] The result callback.
  901. * @return {Promise} returns Promise if no callback passed
  902. */
  903. explain(verbosity, callback) {
  904. if (typeof verbosity === 'function') (callback = verbosity), (verbosity = true);
  905. if (verbosity === undefined) verbosity = true;
  906. if (!this.operation || !this.operation.hasAspect(Aspect.EXPLAINABLE)) {
  907. throw new MongoError('This command cannot be explained');
  908. }
  909. this.operation.explain = new Explain(verbosity);
  910. return maybePromise(this, callback, cb => {
  911. CoreCursor.prototype._next.apply(this, [cb]);
  912. });
  913. }
  914. /**
  915. * Return the cursor logger
  916. * @method
  917. * @return {Logger} return the cursor logger
  918. * @ignore
  919. */
  920. getLogger() {
  921. return this.logger;
  922. }
  923. }
  924. /**
  925. * Cursor stream data event, fired for each document in the cursor.
  926. *
  927. * @event Cursor#data
  928. * @type {object}
  929. */
  930. /**
  931. * Cursor stream end event
  932. *
  933. * @event Cursor#end
  934. * @type {null}
  935. */
  936. /**
  937. * Cursor stream close event
  938. *
  939. * @event Cursor#close
  940. * @type {null}
  941. */
  942. /**
  943. * Cursor stream readable event
  944. *
  945. * @event Cursor#readable
  946. * @type {null}
  947. */
  948. // aliases
  949. Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;
  950. // deprecated methods
  951. deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.');
  952. deprecate(
  953. Cursor.prototype.maxScan,
  954. 'Cursor.maxScan is deprecated, and will be removed in a later version'
  955. );
  956. deprecate(
  957. Cursor.prototype.snapshot,
  958. 'Cursor Snapshot is deprecated, and will be removed in a later version'
  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. module.exports = Cursor;