cursor.js 39 KB

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