3 var inherits = require('util').inherits
4 , f = require('util').format
5 , toError = require('./utils').toError
6 , getSingleProperty = require('./utils').getSingleProperty
7 , formattedOrderClause = require('./utils').formattedOrderClause
8 , handleCallback = require('./utils').handleCallback
9 , Logger = require('mongodb-core').Logger
10 , EventEmitter = require('events').EventEmitter
11 , ReadPreference = require('./read_preference')
12 , MongoError = require('mongodb-core').MongoError
13 , Readable = require('stream').Readable || require('readable-stream').Readable
14 , Define = require('./metadata')
15 , CoreCursor = require('./cursor')
16 , Query = require('mongodb-core').Query
17 , CoreReadPreference = require('mongodb-core').ReadPreference;
20 * @fileOverview The **CommandCursor** class is an internal class that embodies a
21 * generalized cursor based on a MongoDB command allowing for iteration over the
22 * results returned. It supports one by one document iteration, conversion to an
23 * array or can be iterated as a Node 0.10.X or higher stream
25 * **CommandCursor Cannot directly be instantiated**
27 * var MongoClient = require('mongodb').MongoClient,
28 * test = require('assert');
30 * var url = 'mongodb://localhost:27017/test';
31 * // Connect using MongoClient
32 * MongoClient.connect(url, function(err, db) {
33 * // Create a collection we want to drop later
34 * var col = db.collection('listCollectionsExample1');
35 * // Insert a bunch of documents
36 * col.insert([{a:1, b:1}
37 * , {a:2, b:2}, {a:3, b:3}
38 * , {a:4, b:4}], {w:1}, function(err, result) {
39 * test.equal(null, err);
41 * // List the database collections available
42 * db.listCollections().toArray(function(err, items) {
43 * test.equal(null, err);
51 * Namespace provided by the browser.
56 * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly)
57 * @class CommandCursor
58 * @extends external:Readable
59 * @fires CommandCursor#data
60 * @fires CommandCursor#end
61 * @fires CommandCursor#close
62 * @fires CommandCursor#readable
63 * @return {CommandCursor} an CommandCursor instance.
65 var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) {
66 CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
68 var state = CommandCursor.INIT;
69 var streamOptions = {};
74 // Get the promiseLibrary
75 var promiseLibrary = options.promiseLibrary;
77 // No promise library selected fall back
79 promiseLibrary = typeof global.Promise == 'function' ?
80 global.Promise : require('es6-promise').Promise;
84 Readable.call(this, {objectMode: true});
93 , streamOptions: streamOptions
105 , topologyOptions: topologyOptions
107 , promiseLibrary: promiseLibrary
112 * CommandCursor stream data event, fired for each document in the cursor.
114 * @event CommandCursor#data
119 * CommandCursor stream end event
121 * @event CommandCursor#end
126 * CommandCursor stream close event
128 * @event CommandCursor#close
133 * CommandCursor stream readable event
135 * @event CommandCursor#readable
139 // Inherit from Readable
140 inherits(CommandCursor, Readable);
142 // Set the methods to inherit from prototype
143 var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray'
144 , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill'
145 , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled'];
147 // Only inherit the types we need
148 for(var i = 0; i < methodsToInherit.length; i++) {
149 CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]];
152 var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true);
155 * Set the ReadPreference for the cursor.
157 * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
158 * @throws {MongoError}
161 CommandCursor.prototype.setReadPreference = function(r) {
162 if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
163 if(this.s.state != CommandCursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
165 if(r instanceof ReadPreference) {
166 this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessMS: r.maxStalenessMS});
167 } else if(typeof r == 'string') {
168 this.s.options.readPreference = new CoreReadPreference(r);
169 } else if(r instanceof CoreReadPreference) {
170 this.s.options.readPreference = r;
176 define.classMethod('setReadPreference', {callback: false, promise:false, returns: [CommandCursor]});
179 * Set the batch size for the cursor.
181 * @param {number} value The batchSize for the cursor.
182 * @throws {MongoError}
183 * @return {CommandCursor}
185 CommandCursor.prototype.batchSize = function(value) {
186 if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
187 if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
188 if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value;
189 this.setCursorBatchSize(value);
193 define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]});
196 * Add a maxTimeMS stage to the aggregation pipeline
198 * @param {number} value The state maxTimeMS value.
199 * @return {CommandCursor}
201 CommandCursor.prototype.maxTimeMS = function(value) {
202 if(this.s.topology.lastIsMaster().minWireVersion > 2) {
203 this.s.cmd.maxTimeMS = value;
208 define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]});
210 CommandCursor.prototype.get = CommandCursor.prototype.toArray;
212 define.classMethod('get', {callback: true, promise:false});
215 define.classMethod('toArray', {callback: true, promise:true});
216 define.classMethod('each', {callback: true, promise:false});
217 define.classMethod('forEach', {callback: true, promise:false});
218 define.classMethod('next', {callback: true, promise:true});
219 define.classMethod('close', {callback: true, promise:true});
220 define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
221 define.classMethod('rewind', {callback: false, promise:false});
222 define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]});
223 define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]});
226 * Get the next available document from the cursor, returns null if no more documents are available.
227 * @function CommandCursor.prototype.next
228 * @param {CommandCursor~resultCallback} [callback] The result callback.
229 * @throws {MongoError}
230 * @return {Promise} returns Promise if no callback passed
234 * The callback format for results
235 * @callback CommandCursor~toArrayResultCallback
236 * @param {MongoError} error An error instance representing the error during the execution.
237 * @param {object[]} documents All the documents the satisfy the cursor.
241 * Returns an array of documents. The caller is responsible for making sure that there
242 * is enough memory to store the results. Note that the array only contain partial
243 * results when this cursor had been previouly accessed.
244 * @method CommandCursor.prototype.toArray
245 * @param {CommandCursor~toArrayResultCallback} [callback] The result callback.
246 * @throws {MongoError}
247 * @return {Promise} returns Promise if no callback passed
251 * The callback format for results
252 * @callback CommandCursor~resultCallback
253 * @param {MongoError} error An error instance representing the error during the execution.
254 * @param {(object|null)} result The result object if the command was executed successfully.
258 * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
259 * not all of the elements will be iterated if this cursor had been previouly accessed.
260 * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
261 * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
262 * at any given time if batch size is specified. Otherwise, the caller is responsible
263 * for making sure that the entire result can fit the memory.
264 * @method CommandCursor.prototype.each
265 * @param {CommandCursor~resultCallback} callback The result callback.
266 * @throws {MongoError}
271 * Close the cursor, sending a KillCursor command and emitting close.
272 * @method CommandCursor.prototype.close
273 * @param {CommandCursor~resultCallback} [callback] The result callback.
274 * @return {Promise} returns Promise if no callback passed
278 * Is the cursor closed
279 * @method CommandCursor.prototype.isClosed
285 * @function CommandCursor.prototype.clone
286 * @return {CommandCursor}
291 * @function CommandCursor.prototype.rewind
292 * @return {CommandCursor}
296 * The callback format for the forEach iterator method
297 * @callback CommandCursor~iteratorCallback
298 * @param {Object} doc An emitted document for the iterator
302 * The callback error format for the forEach iterator method
303 * @callback CommandCursor~endCallback
304 * @param {MongoError} error An error instance representing the error during the execution.
308 * Iterates over all the documents for this cursor using the iterator, callback pattern.
309 * @method CommandCursor.prototype.forEach
310 * @param {CommandCursor~iteratorCallback} iterator The iteration callback.
311 * @param {CommandCursor~endCallback} callback The end callback.
312 * @throws {MongoError}
316 CommandCursor.INIT = 0;
317 CommandCursor.OPEN = 1;
318 CommandCursor.CLOSED = 2;
320 module.exports = CommandCursor;