UNPKG

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