command_cursor.js 9.2 KB

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