cursor.js 36 KB

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