Source: lib/command_cursor.js

  1. "use strict";
  2. var inherits = require('util').inherits
  3. , ReadPreference = require('./read_preference')
  4. , MongoError = require('mongodb-core').MongoError
  5. , Readable = require('stream').Readable || require('readable-stream').Readable
  6. , Define = require('./metadata')
  7. , CoreCursor = require('./cursor')
  8. , CoreReadPreference = require('mongodb-core').ReadPreference;
  9. /**
  10. * @fileOverview The **CommandCursor** class is an internal class that embodies a
  11. * generalized cursor based on a MongoDB command allowing for iteration over the
  12. * results returned. It supports one by one document iteration, conversion to an
  13. * array or can be iterated as a Node 0.10.X or higher stream
  14. *
  15. * **CommandCursor Cannot directly be instantiated**
  16. * @example
  17. * var MongoClient = require('mongodb').MongoClient,
  18. * test = require('assert');
  19. * // Connection url
  20. * var url = 'mongodb://localhost:27017/test';
  21. * // Connect using MongoClient
  22. * MongoClient.connect(url, function(err, db) {
  23. * // Create a collection we want to drop later
  24. * var col = db.collection('listCollectionsExample1');
  25. * // Insert a bunch of documents
  26. * col.insert([{a:1, b:1}
  27. * , {a:2, b:2}, {a:3, b:3}
  28. * , {a:4, b:4}], {w:1}, function(err, result) {
  29. * test.equal(null, err);
  30. *
  31. * // List the database collections available
  32. * db.listCollections().toArray(function(err, items) {
  33. * test.equal(null, err);
  34. * db.close();
  35. * });
  36. * });
  37. * });
  38. */
  39. /**
  40. * Namespace provided by the browser.
  41. * @external Readable
  42. */
  43. /**
  44. * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
  45. * @class CommandCursor
  46. * @extends external:Readable
  47. * @fires CommandCursor#data
  48. * @fires CommandCursor#end
  49. * @fires CommandCursor#close
  50. * @fires CommandCursor#readable
  51. * @return {CommandCursor} an CommandCursor instance.
  52. */
  53. var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
  54. CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
  55. var state = CommandCursor.INIT;
  56. var streamOptions = {};
  57. // MaxTimeMS
  58. var maxTimeMS = null;
  59. // Get the promiseLibrary
  60. var promiseLibrary = options.promiseLibrary;
  61. // No promise library selected fall back
  62. if(!promiseLibrary) {
  63. promiseLibrary = typeof global.Promise == 'function' ?
  64. global.Promise : require('es6-promise').Promise;
  65. }
  66. // Set up
  67. Readable.call(this, {objectMode: true});
  68. // Internal state
  69. this.s = {
  70. // MaxTimeMS
  71. maxTimeMS: maxTimeMS
  72. // State
  73. , state: state
  74. // Stream options
  75. , streamOptions: streamOptions
  76. // BSON
  77. , bson: bson
  78. // Namespace
  79. , ns: ns
  80. // Command
  81. , cmd: cmd
  82. // Options
  83. , options: options
  84. // Topology
  85. , topology: topology
  86. // Topology Options
  87. , topologyOptions: topologyOptions
  88. // Promise library
  89. , promiseLibrary: promiseLibrary
  90. }
  91. }
  92. /**
  93. * CommandCursor stream data event, fired for each document in the cursor.
  94. *
  95. * @event CommandCursor#data
  96. * @type {object}
  97. */
  98. /**
  99. * CommandCursor stream end event
  100. *
  101. * @event CommandCursor#end
  102. * @type {null}
  103. */
  104. /**
  105. * CommandCursor stream close event
  106. *
  107. * @event CommandCursor#close
  108. * @type {null}
  109. */
  110. /**
  111. * CommandCursor stream readable event
  112. *
  113. * @event CommandCursor#readable
  114. * @type {null}
  115. */
  116. // Inherit from Readable
  117. inherits(CommandCursor, Readable);
  118. // Set the methods to inherit from prototype
  119. var methodsToInherit = ['_next', 'next', 'hasNext', 'each', 'forEach', 'toArray'
  120. , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill', 'setCursorBatchSize'
  121. , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled'];
  122. // Only inherit the types we need
  123. for(var i = 0; i < methodsToInherit.length; i++) {
  124. CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]];
  125. }
  126. var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true);
  127. /**
  128. * Set the ReadPreference for the cursor.
  129. * @method
  130. * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
  131. * @throws {MongoError}
  132. * @return {Cursor}
  133. */
  134. CommandCursor.prototype.setReadPreference = function(r) {
  135. if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  136. if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
  137. if(r instanceof ReadPreference) {
  138. this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  139. } else if(typeof r == 'string') {
  140. this.s.options.readPreference = new CoreReadPreference(r);
  141. } else if(r instanceof CoreReadPreference) {
  142. this.s.options.readPreference = r;
  143. }
  144. return this;
  145. }
  146. define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]});
  147. /**
  148. * Set the batch size for the cursor.
  149. * @method
  150. * @param {number} value The batchSize for the cursor.
  151. * @throws {MongoError}
  152. * @return {CommandCursor}
  153. */
  154. CommandCursor.prototype.batchSize = function(value) {
  155. if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
  156. if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
  157. if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
  158. this.setCursorBatchSize(value);
  159. return this;
  160. }
  161. define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]});
  162. /**
  163. * Add a maxTimeMS stage to the aggregation pipeline
  164. * @method
  165. * @param {number} value The state maxTimeMS value.
  166. * @return {CommandCursor}
  167. */
  168. CommandCursor.prototype.maxTimeMS = function(value) {
  169. if(this.s.topology.lastIsMaster().minWireVersion > 2) {
  170. this.s.cmd.maxTimeMS = value;
  171. }
  172. return this;
  173. }
  174. define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]});
  175. CommandCursor.prototype.get = CommandCursor.prototype.toArray;
  176. define.classMethod('get', {callback: true, promise:false});
  177. // Inherited methods
  178. define.classMethod('toArray', {callback: true, promise:true});
  179. define.classMethod('each', {callback: true, promise:false});
  180. define.classMethod('forEach', {callback: true, promise:false});
  181. define.classMethod('next', {callback: true, promise:true});
  182. define.classMethod('hasNext', {callback: true, promise:true});
  183. define.classMethod('close', {callback: true, promise:true});
  184. define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
  185. define.classMethod('rewind', {callback: false, promise:false});
  186. define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]});
  187. define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]});
  188. /**
  189. * Get the next available document from the cursor, returns null if no more documents are available.
  190. * @function CommandCursor.prototype.next
  191. * @param {CommandCursor~resultCallback} [callback] The result callback.
  192. * @throws {MongoError}
  193. * @return {Promise} returns Promise if no callback passed
  194. */
  195. /**
  196. * Check if there is any document still available in the cursor
  197. * @function CommandCursor.prototype.hasNext
  198. * @param {CommandCursor~resultCallback} [callback] The result callback.
  199. * @throws {MongoError}
  200. * @return {Promise} returns Promise if no callback passed
  201. */
  202. /**
  203. * The callback format for results
  204. * @callback CommandCursor~toArrayResultCallback
  205. * @param {MongoError} error An error instance representing the error during the execution.
  206. * @param {object[]} documents All the documents the satisfy the cursor.
  207. */
  208. /**
  209. * Returns an array of documents. The caller is responsible for making sure that there
  210. * is enough memory to store the results. Note that the array only contain partial
  211. * results when this cursor had been previously accessed.
  212. * @method CommandCursor.prototype.toArray
  213. * @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
  214. * @throws {MongoError}
  215. * @return {Promise} returns Promise if no callback passed
  216. */
  217. /**
  218. * The callback format for results
  219. * @callback CommandCursor~resultCallback
  220. * @param {MongoError} error An error instance representing the error during the execution.
  221. * @param {(object|null)} result The result object if the command was executed successfully.
  222. */
  223. /**
  224. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  225. * not all of the elements will be iterated if this cursor had been previously accessed.
  226. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  227. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  228. * at any given time if batch size is specified. Otherwise, the caller is responsible
  229. * for making sure that the entire result can fit the memory.
  230. * @method CommandCursor.prototype.each
  231. * @param {CommandCursor~resultCallback} callback The result callback.
  232. * @throws {MongoError}
  233. * @return {null}
  234. */
  235. /**
  236. * Close the cursor, sending a KillCursor command and emitting close.
  237. * @method CommandCursor.prototype.close
  238. * @param {CommandCursor~resultCallback} [callback] The result callback.
  239. * @return {Promise} returns Promise if no callback passed
  240. */
  241. /**
  242. * Is the cursor closed
  243. * @method CommandCursor.prototype.isClosed
  244. * @return {boolean}
  245. */
  246. /**
  247. * Clone the cursor
  248. * @function CommandCursor.prototype.clone
  249. * @return {CommandCursor}
  250. */
  251. /**
  252. * Resets the cursor
  253. * @function CommandCursor.prototype.rewind
  254. * @return {CommandCursor}
  255. */
  256. /**
  257. * The callback format for the forEach iterator method
  258. * @callback CommandCursor~iteratorCallback
  259. * @param {Object} doc An emitted document for the iterator
  260. */
  261. /**
  262. * The callback error format for the forEach iterator method
  263. * @callback CommandCursor~endCallback
  264. * @param {MongoError} error An error instance representing the error during the execution.
  265. */
  266. /*
  267. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  268. * @method CommandCursor.prototype.forEach
  269. * @param {CommandCursor~iteratorCallback} iterator The iteration callback.
  270. * @param {CommandCursor~endCallback} callback The end callback.
  271. * @throws {MongoError}
  272. * @return {null}
  273. */
  274. CommandCursor.INIT = 0;
  275. CommandCursor.OPEN = 1;
  276. CommandCursor.CLOSED = 2;
  277. module.exports = CommandCursor;