command_cursor.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. 'use strict';
  2. const ReadPreference = require('./core').ReadPreference;
  3. const MongoError = require('./core').MongoError;
  4. const Cursor = require('./cursor');
  5. const CursorState = require('./core/cursor').CursorState;
  6. /**
  7. * @fileOverview The **CommandCursor** class is an internal class that embodies a
  8. * generalized cursor based on a MongoDB command allowing for iteration over the
  9. * results returned. It supports one by one document iteration, conversion to an
  10. * array or can be iterated as a Node 0.10.X or higher stream
  11. *
  12. * **CommandCursor Cannot directly be instantiated**
  13. * @example
  14. * const MongoClient = require('mongodb').MongoClient;
  15. * const test = require('assert');
  16. * // Connection url
  17. * const url = 'mongodb://localhost:27017';
  18. * // Database Name
  19. * const dbName = 'test';
  20. * // Connect using MongoClient
  21. * MongoClient.connect(url, function(err, client) {
  22. * // Create a collection we want to drop later
  23. * const col = client.db(dbName).collection('listCollectionsExample1');
  24. * // Insert a bunch of documents
  25. * col.insert([{a:1, b:1}
  26. * , {a:2, b:2}, {a:3, b:3}
  27. * , {a:4, b:4}], {w:1}, function(err, result) {
  28. * test.equal(null, err);
  29. * // List the database collections available
  30. * db.listCollections().toArray(function(err, items) {
  31. * test.equal(null, err);
  32. * client.close();
  33. * });
  34. * });
  35. * });
  36. */
  37. /**
  38. * Namespace provided by the browser.
  39. * @external Readable
  40. */
  41. /**
  42. * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
  43. * @class CommandCursor
  44. * @extends external:Readable
  45. * @fires CommandCursor#data
  46. * @fires CommandCursor#end
  47. * @fires CommandCursor#close
  48. * @fires CommandCursor#readable
  49. * @return {CommandCursor} an CommandCursor instance.
  50. */
  51. class CommandCursor extends Cursor {
  52. constructor(topology, ns, cmd, options) {
  53. super(topology, ns, cmd, options);
  54. }
  55. /**
  56. * Set the ReadPreference for the cursor.
  57. * @method
  58. * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
  59. * @throws {MongoError}
  60. * @return {Cursor}
  61. */
  62. setReadPreference(readPreference) {
  63. if (this.s.state === CursorState.CLOSED || this.isDead()) {
  64. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  65. }
  66. if (this.s.state !== CursorState.INIT) {
  67. throw MongoError.create({
  68. message: 'cannot change cursor readPreference after cursor has been accessed',
  69. driver: true
  70. });
  71. }
  72. if (readPreference instanceof ReadPreference) {
  73. this.options.readPreference = readPreference;
  74. } else if (typeof readPreference === 'string') {
  75. this.options.readPreference = new ReadPreference(readPreference);
  76. } else {
  77. throw new TypeError('Invalid read preference: ' + readPreference);
  78. }
  79. return this;
  80. }
  81. /**
  82. * Set the batch size for the cursor.
  83. * @method
  84. * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}.
  85. * @throws {MongoError}
  86. * @return {CommandCursor}
  87. */
  88. batchSize(value) {
  89. if (this.s.state === CursorState.CLOSED || this.isDead()) {
  90. throw MongoError.create({ message: 'Cursor is closed', driver: true });
  91. }
  92. if (typeof value !== 'number') {
  93. throw MongoError.create({ message: 'batchSize requires an integer', driver: true });
  94. }
  95. if (this.cmd.cursor) {
  96. this.cmd.cursor.batchSize = value;
  97. }
  98. this.setCursorBatchSize(value);
  99. return this;
  100. }
  101. /**
  102. * Add a maxTimeMS stage to the aggregation pipeline
  103. * @method
  104. * @param {number} value The state maxTimeMS value.
  105. * @return {CommandCursor}
  106. */
  107. maxTimeMS(value) {
  108. if (this.topology.lastIsMaster().minWireVersion > 2) {
  109. this.cmd.maxTimeMS = value;
  110. }
  111. return this;
  112. }
  113. /**
  114. * Return the cursor logger
  115. * @method
  116. * @return {Logger} return the cursor logger
  117. * @ignore
  118. */
  119. getLogger() {
  120. return this.logger;
  121. }
  122. }
  123. // aliases
  124. CommandCursor.prototype.get = CommandCursor.prototype.toArray;
  125. /**
  126. * CommandCursor stream data event, fired for each document in the cursor.
  127. *
  128. * @event CommandCursor#data
  129. * @type {object}
  130. */
  131. /**
  132. * CommandCursor stream end event
  133. *
  134. * @event CommandCursor#end
  135. * @type {null}
  136. */
  137. /**
  138. * CommandCursor stream close event
  139. *
  140. * @event CommandCursor#close
  141. * @type {null}
  142. */
  143. /**
  144. * CommandCursor stream readable event
  145. *
  146. * @event CommandCursor#readable
  147. * @type {null}
  148. */
  149. /**
  150. * Get the next available document from the cursor, returns null if no more documents are available.
  151. * @function CommandCursor.prototype.next
  152. * @param {CommandCursor~resultCallback} [callback] The result callback.
  153. * @throws {MongoError}
  154. * @return {Promise} returns Promise if no callback passed
  155. */
  156. /**
  157. * Check if there is any document still available in the cursor
  158. * @function CommandCursor.prototype.hasNext
  159. * @param {CommandCursor~resultCallback} [callback] The result callback.
  160. * @throws {MongoError}
  161. * @return {Promise} returns Promise if no callback passed
  162. */
  163. /**
  164. * The callback format for results
  165. * @callback CommandCursor~toArrayResultCallback
  166. * @param {MongoError} error An error instance representing the error during the execution.
  167. * @param {object[]} documents All the documents the satisfy the cursor.
  168. */
  169. /**
  170. * Returns an array of documents. The caller is responsible for making sure that there
  171. * is enough memory to store the results. Note that the array only contain partial
  172. * results when this cursor had been previously accessed.
  173. * @method CommandCursor.prototype.toArray
  174. * @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
  175. * @throws {MongoError}
  176. * @return {Promise} returns Promise if no callback passed
  177. */
  178. /**
  179. * The callback format for results
  180. * @callback CommandCursor~resultCallback
  181. * @param {MongoError} error An error instance representing the error during the execution.
  182. * @param {(object|null)} result The result object if the command was executed successfully.
  183. */
  184. /**
  185. * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
  186. * not all of the elements will be iterated if this cursor had been previously accessed.
  187. * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
  188. * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
  189. * at any given time if batch size is specified. Otherwise, the caller is responsible
  190. * for making sure that the entire result can fit the memory.
  191. * @method CommandCursor.prototype.each
  192. * @param {CommandCursor~resultCallback} callback The result callback.
  193. * @throws {MongoError}
  194. * @return {null}
  195. */
  196. /**
  197. * Close the cursor, sending a KillCursor command and emitting close.
  198. * @method CommandCursor.prototype.close
  199. * @param {CommandCursor~resultCallback} [callback] The result callback.
  200. * @return {Promise} returns Promise if no callback passed
  201. */
  202. /**
  203. * Is the cursor closed
  204. * @method CommandCursor.prototype.isClosed
  205. * @return {boolean}
  206. */
  207. /**
  208. * Clone the cursor
  209. * @function CommandCursor.prototype.clone
  210. * @return {CommandCursor}
  211. */
  212. /**
  213. * Resets the cursor
  214. * @function CommandCursor.prototype.rewind
  215. * @return {CommandCursor}
  216. */
  217. /**
  218. * The callback format for the forEach iterator method
  219. * @callback CommandCursor~iteratorCallback
  220. * @param {Object} doc An emitted document for the iterator
  221. */
  222. /**
  223. * The callback error format for the forEach iterator method
  224. * @callback CommandCursor~endCallback
  225. * @param {MongoError} error An error instance representing the error during the execution.
  226. */
  227. /*
  228. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  229. * @method CommandCursor.prototype.forEach
  230. * @param {CommandCursor~iteratorCallback} iterator The iteration callback.
  231. * @param {CommandCursor~endCallback} callback The end callback.
  232. * @throws {MongoError}
  233. * @return {null}
  234. */
  235. module.exports = CommandCursor;