1
1
'use strict' ;
2
2
3
3
const common = require ( './common' ) ;
4
+ const BulkOperationBase = common . BulkOperationBase ;
4
5
const utils = require ( '../utils' ) ;
5
- const toError = require ( '../utils' ) . toError ;
6
- const handleCallback = require ( '../utils' ) . handleCallback ;
7
- const shallowClone = utils . shallowClone ;
6
+ const toError = utils . toError ;
7
+ const handleCallback = utils . handleCallback ;
8
8
const BulkWriteResult = common . BulkWriteResult ;
9
- const ObjectID = require ( 'mongodb-core' ) . BSON . ObjectID ;
10
- const BSON = require ( 'mongodb-core' ) . BSON ;
11
9
const Batch = common . Batch ;
12
10
const mergeBatchResults = common . mergeBatchResults ;
13
11
const executeOperation = utils . executeOperation ;
14
- const BulkWriteError = require ( './common' ) . BulkWriteError ;
15
- const applyWriteConcern = utils . applyWriteConcern ;
16
12
const MongoWriteConcernError = require ( 'mongodb-core' ) . MongoWriteConcernError ;
17
13
const handleMongoWriteConcernError = require ( './common' ) . handleMongoWriteConcernError ;
18
-
19
- var bson = new BSON ( [
20
- BSON . Binary ,
21
- BSON . Code ,
22
- BSON . DBRef ,
23
- BSON . Decimal128 ,
24
- BSON . Double ,
25
- BSON . Int32 ,
26
- BSON . Long ,
27
- BSON . Map ,
28
- BSON . MaxKey ,
29
- BSON . MinKey ,
30
- BSON . ObjectId ,
31
- BSON . BSONRegExp ,
32
- BSON . Symbol ,
33
- BSON . Timestamp
34
- ] ) ;
35
-
36
- /**
37
- * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly)
38
- * @class
39
- * @property {number } length Get the number of operations in the bulk.
40
- * @return {FindOperatorsUnordered } a FindOperatorsUnordered instance.
41
- */
42
- var FindOperatorsUnordered = function ( self ) {
43
- this . s = self . s ;
44
- } ;
14
+ const bson = common . bson ;
45
15
46
16
/**
47
- * Add a single update document to the bulk operation
17
+ * Add to internal list of Operations
48
18
*
49
- * @method
50
- * @param {object } updateDocument update operations
51
- * @throws {MongoError }
52
- * @return {FindOperatorsUnordered }
53
- */
54
- FindOperatorsUnordered . prototype . update = function ( updateDocument ) {
55
- // Perform upsert
56
- var upsert = typeof this . s . currentOp . upsert === 'boolean' ? this . s . currentOp . upsert : false ;
57
-
58
- // Establish the update command
59
- var document = {
60
- q : this . s . currentOp . selector ,
61
- u : updateDocument ,
62
- multi : true ,
63
- upsert : upsert
64
- } ;
65
-
66
- // Clear out current Op
67
- this . s . currentOp = null ;
68
- // Add the update document to the list
69
- return addToOperationsList ( this , common . UPDATE , document ) ;
70
- } ;
71
-
72
- /**
73
- * Add a single update one document to the bulk operation
74
- *
75
- * @method
76
- * @param {object } updateDocument update operations
77
- * @throws {MongoError }
78
- * @return {FindOperatorsUnordered }
79
- */
80
- FindOperatorsUnordered . prototype . updateOne = function ( updateDocument ) {
81
- // Perform upsert
82
- var upsert = typeof this . s . currentOp . upsert === 'boolean' ? this . s . currentOp . upsert : false ;
83
-
84
- // Establish the update command
85
- var document = {
86
- q : this . s . currentOp . selector ,
87
- u : updateDocument ,
88
- multi : false ,
89
- upsert : upsert
90
- } ;
91
-
92
- // Clear out current Op
93
- this . s . currentOp = null ;
94
- // Add the update document to the list
95
- return addToOperationsList ( this , common . UPDATE , document ) ;
96
- } ;
97
-
98
- /**
99
- * Add a replace one operation to the bulk operation
100
- *
101
- * @method
102
- * @param {object } updateDocument the new document to replace the existing one with
103
- * @throws {MongoError }
104
- * @return {FindOperatorsUnordered }
105
- */
106
- FindOperatorsUnordered . prototype . replaceOne = function ( updateDocument ) {
107
- this . updateOne ( updateDocument ) ;
108
- } ;
109
-
110
- /**
111
- * Upsert modifier for update bulk operation
112
- *
113
- * @method
114
- * @throws {MongoError }
115
- * @return {FindOperatorsUnordered }
116
- */
117
- FindOperatorsUnordered . prototype . upsert = function ( ) {
118
- this . s . currentOp . upsert = true ;
119
- return this ;
120
- } ;
121
-
122
- /**
123
- * Add a remove one operation to the bulk operation
124
- *
125
- * @method
126
- * @throws {MongoError }
127
- * @return {FindOperatorsUnordered }
128
- */
129
- FindOperatorsUnordered . prototype . removeOne = function ( ) {
130
- // Establish the update command
131
- var document = {
132
- q : this . s . currentOp . selector ,
133
- limit : 1
134
- } ;
135
-
136
- // Clear out current Op
137
- this . s . currentOp = null ;
138
- // Add the remove document to the list
139
- return addToOperationsList ( this , common . REMOVE , document ) ;
140
- } ;
141
-
142
- /**
143
- * Add a remove operation to the bulk operation
144
- *
145
- * @method
146
- * @throws {MongoError }
147
- * @return {FindOperatorsUnordered }
19
+ * @param {UnorderedBulkOperation } bulkOperation
20
+ * @param {number } docType number indicating the document type
21
+ * @param {object } document
22
+ * @return {UnorderedBulkOperation }
148
23
*/
149
- FindOperatorsUnordered . prototype . remove = function ( ) {
150
- // Establish the update command
151
- var document = {
152
- q : this . s . currentOp . selector ,
153
- limit : 0
154
- } ;
155
-
156
- // Clear out current Op
157
- this . s . currentOp = null ;
158
- // Add the remove document to the list
159
- return addToOperationsList ( this , common . REMOVE , document ) ;
160
- } ;
161
-
162
- //
163
- // Add to the operations list
164
- //
165
- var addToOperationsList = function ( _self , docType , document ) {
24
+ function addToOperationsList ( bulkOperation , docType , document ) {
166
25
// Get the bsonSize
167
- var bsonSize = bson . calculateObjectSize ( document , {
26
+ const bsonSize = bson . calculateObjectSize ( document , {
168
27
checkKeys : false
169
28
} ) ;
170
29
// Throw error if the doc is bigger than the max BSON size
171
- if ( bsonSize >= _self . s . maxBatchSizeBytes )
172
- throw toError ( 'document is larger than the maximum size ' + _self . s . maxBatchSizeBytes ) ;
30
+ if ( bsonSize >= bulkOperation . s . maxBatchSizeBytes )
31
+ throw toError ( 'document is larger than the maximum size ' + bulkOperation . s . maxBatchSizeBytes ) ;
173
32
// Holds the current batch
174
- _self . s . currentBatch = null ;
33
+ bulkOperation . s . currentBatch = null ;
175
34
// Get the right type of batch
176
35
if ( docType === common . INSERT ) {
177
- _self . s . currentBatch = _self . s . currentInsertBatch ;
36
+ bulkOperation . s . currentBatch = bulkOperation . s . currentInsertBatch ;
178
37
} else if ( docType === common . UPDATE ) {
179
- _self . s . currentBatch = _self . s . currentUpdateBatch ;
38
+ bulkOperation . s . currentBatch = bulkOperation . s . currentUpdateBatch ;
180
39
} else if ( docType === common . REMOVE ) {
181
- _self . s . currentBatch = _self . s . currentRemoveBatch ;
40
+ bulkOperation . s . currentBatch = bulkOperation . s . currentRemoveBatch ;
182
41
}
183
42
184
43
// Create a new batch object if we don't have a current one
185
- if ( _self . s . currentBatch == null ) _self . s . currentBatch = new Batch ( docType , _self . s . currentIndex ) ;
44
+ if ( bulkOperation . s . currentBatch == null )
45
+ bulkOperation . s . currentBatch = new Batch ( docType , bulkOperation . s . currentIndex ) ;
186
46
187
47
// Check if we need to create a new batch
188
48
if (
189
- _self . s . currentBatch . size + 1 >= _self . s . maxWriteBatchSize ||
190
- _self . s . currentBatch . sizeBytes + bsonSize >= _self . s . maxBatchSizeBytes ||
191
- _self . s . currentBatch . batchType !== docType
49
+ bulkOperation . s . currentBatch . size + 1 >= bulkOperation . s . maxWriteBatchSize ||
50
+ bulkOperation . s . currentBatch . sizeBytes + bsonSize >= bulkOperation . s . maxBatchSizeBytes ||
51
+ bulkOperation . s . currentBatch . batchType !== docType
192
52
) {
193
53
// Save the batch to the execution stack
194
- _self . s . batches . push ( _self . s . currentBatch ) ;
54
+ bulkOperation . s . batches . push ( bulkOperation . s . currentBatch ) ;
195
55
196
56
// Create a new batch
197
- _self . s . currentBatch = new Batch ( docType , _self . s . currentIndex ) ;
57
+ bulkOperation . s . currentBatch = new Batch ( docType , bulkOperation . s . currentIndex ) ;
198
58
}
199
59
200
60
// We have an array of documents
201
61
if ( Array . isArray ( document ) ) {
202
62
throw toError ( 'operation passed in cannot be an Array' ) ;
203
63
} else {
204
- _self . s . currentBatch . operations . push ( document ) ;
205
- _self . s . currentBatch . originalIndexes . push ( _self . s . currentIndex ) ;
206
- _self . s . currentIndex = _self . s . currentIndex + 1 ;
64
+ bulkOperation . s . currentBatch . operations . push ( document ) ;
65
+ bulkOperation . s . currentBatch . originalIndexes . push ( bulkOperation . s . currentIndex ) ;
66
+ bulkOperation . s . currentIndex = bulkOperation . s . currentIndex + 1 ;
207
67
}
208
68
209
69
// Save back the current Batch to the right type
210
70
if ( docType === common . INSERT ) {
211
- _self . s . currentInsertBatch = _self . s . currentBatch ;
212
- _self . s . bulkResult . insertedIds . push ( {
213
- index : _self . s . bulkResult . insertedIds . length ,
71
+ bulkOperation . s . currentInsertBatch = bulkOperation . s . currentBatch ;
72
+ bulkOperation . s . bulkResult . insertedIds . push ( {
73
+ index : bulkOperation . s . bulkResult . insertedIds . length ,
214
74
_id : document . _id
215
75
} ) ;
216
76
} else if ( docType === common . UPDATE ) {
217
- _self . s . currentUpdateBatch = _self . s . currentBatch ;
77
+ bulkOperation . s . currentUpdateBatch = bulkOperation . s . currentBatch ;
218
78
} else if ( docType === common . REMOVE ) {
219
- _self . s . currentRemoveBatch = _self . s . currentBatch ;
79
+ bulkOperation . s . currentRemoveBatch = bulkOperation . s . currentBatch ;
220
80
}
221
81
222
82
// Update current batch size
223
- _self . s . currentBatch . size = _self . s . currentBatch . size + 1 ;
224
- _self . s . currentBatch . sizeBytes = _self . s . currentBatch . sizeBytes + bsonSize ;
83
+ bulkOperation . s . currentBatch . size = bulkOperation . s . currentBatch . size + 1 ;
84
+ bulkOperation . s . currentBatch . sizeBytes = bulkOperation . s . currentBatch . sizeBytes + bsonSize ;
225
85
226
- // Return self
227
- return _self ;
228
- } ;
86
+ // Return bulkOperation
87
+ return bulkOperation ;
88
+ }
229
89
230
90
/**
231
91
* Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly)
232
92
* @class
233
93
* @property {number } length Get the number of operations in the bulk.
234
94
* @return {UnorderedBulkOperation } a UnorderedBulkOperation instance.
235
95
*/
236
- var UnorderedBulkOperation = function ( topology , collection , options ) {
237
- options = options == null ? { } : options ;
238
-
239
- // Get the namesspace for the write operations
240
- var namespace = collection . collectionName ;
241
- // Used to mark operation as executed
242
- var executed = false ;
243
-
244
- // Current item
245
- // var currentBatch = null;
246
- var currentOp = null ;
247
-
248
- // Handle to the bson serializer, used to calculate running sizes
249
- var bson = topology . bson ;
250
-
251
- // Set max byte size
252
- var maxBatchSizeBytes =
253
- topology . isMasterDoc && topology . isMasterDoc . maxBsonObjectSize
254
- ? topology . isMasterDoc . maxBsonObjectSize
255
- : 1024 * 1025 * 16 ;
256
- var maxWriteBatchSize =
257
- topology . isMasterDoc && topology . isMasterDoc . maxWriteBatchSize
258
- ? topology . isMasterDoc . maxWriteBatchSize
259
- : 1000 ;
260
-
261
- // Get the write concern
262
- var writeConcern = applyWriteConcern ( shallowClone ( options ) , { collection : collection } , options ) ;
263
- writeConcern = writeConcern . writeConcern ;
264
-
265
- // Get the promiseLibrary
266
- var promiseLibrary = options . promiseLibrary || Promise ;
267
-
268
- // Final results
269
- var bulkResult = {
270
- ok : 1 ,
271
- writeErrors : [ ] ,
272
- writeConcernErrors : [ ] ,
273
- insertedIds : [ ] ,
274
- nInserted : 0 ,
275
- nUpserted : 0 ,
276
- nMatched : 0 ,
277
- nModified : 0 ,
278
- nRemoved : 0 ,
279
- upserted : [ ]
280
- } ;
281
-
282
- // Internal state
283
- this . s = {
284
- // Final result
285
- bulkResult : bulkResult ,
286
- // Current batch state
287
- currentInsertBatch : null ,
288
- currentUpdateBatch : null ,
289
- currentRemoveBatch : null ,
290
- currentBatch : null ,
291
- currentIndex : 0 ,
292
- batches : [ ] ,
293
- // Write concern
294
- writeConcern : writeConcern ,
295
- // Max batch size options
296
- maxBatchSizeBytes : maxBatchSizeBytes ,
297
- maxWriteBatchSize : maxWriteBatchSize ,
298
- // Namespace
299
- namespace : namespace ,
300
- // BSON
301
- bson : bson ,
302
- // Topology
303
- topology : topology ,
304
- // Options
305
- options : options ,
306
- // Current operation
307
- currentOp : currentOp ,
308
- // Executed
309
- executed : executed ,
310
- // Collection
311
- collection : collection ,
312
- // Promise Library
313
- promiseLibrary : promiseLibrary ,
314
- // check keys
315
- checkKeys : typeof options . checkKeys === 'boolean' ? options . checkKeys : true
316
- } ;
317
- // bypass Validation
318
- if ( options . bypassDocumentValidation === true ) {
319
- this . s . bypassDocumentValidation = true ;
320
- }
321
- } ;
322
-
323
- /**
324
- * Add a single insert document to the bulk operation
325
- *
326
- * @param {object } document the document to insert
327
- * @throws {MongoError }
328
- * @return {UnorderedBulkOperation }
329
- */
330
- UnorderedBulkOperation . prototype . insert = function ( document ) {
331
- if ( this . s . collection . s . db . options . forceServerObjectId !== true && document . _id == null )
332
- document . _id = new ObjectID ( ) ;
333
- return addToOperationsList ( this , common . INSERT , document ) ;
334
- } ;
96
+ class UnorderedBulkOperation extends BulkOperationBase {
97
+ constructor ( topology , collection , options ) {
98
+ options = options || { } ;
99
+ options = Object . assign ( options , { addToOperationsList } ) ;
100
+
101
+ super ( topology , collection , options , false ) ;
102
+ }
103
+
104
+ /**
105
+ * The callback format for results
106
+ * @callback UnorderedBulkOperation~resultCallback
107
+ * @param {MongoError } error An error instance representing the error during the execution.
108
+ * @param {BulkWriteResult } result The bulk write result.
109
+ */
110
+
111
+ /**
112
+ * Execute the ordered bulk operation
113
+ *
114
+ * @method
115
+ * @param {object } [options] Optional settings.
116
+ * @param {(number|string) } [options.w] The write concern.
117
+ * @param {number } [options.wtimeout] The write concern timeout.
118
+ * @param {boolean } [options.j=false] Specify a journal write concern.
119
+ * @param {boolean } [options.fsync=false] Specify a file sync write concern.
120
+ * @param {UnorderedBulkOperation~resultCallback } [callback] The result callback
121
+ * @throws {MongoError }
122
+ * @return {Promise } returns Promise if no callback passed
123
+ */
124
+ execute ( _writeConcern , options , callback ) {
125
+ const ret = this . bulkExecute ( _writeConcern , options , callback ) ;
126
+ options = ret . options ;
127
+ callback = ret . callback ;
128
+
129
+ return executeOperation ( this . s . topology , executeBatches , [ this , options , callback ] ) ;
130
+ }
131
+ }
335
132
336
133
/**
337
- * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne
134
+ * Execute the command
338
135
*
339
- * @method
340
- * @param {object } selector The selector for the bulk operation.
341
- * @throws { MongoError }
342
- * @return { FindOperatorsUnordered }
136
+ * @param { UnorderedBulkOperation } bulkOperation
137
+ * @param {object } batch
138
+ * @param { object } options
139
+ * @param { function } callback
343
140
*/
344
- UnorderedBulkOperation . prototype . find = function ( selector ) {
345
- if ( ! selector ) {
346
- throw toError ( 'Bulk find operation must specify a selector' ) ;
347
- }
348
-
349
- // Save a current selector
350
- this . s . currentOp = {
351
- selector : selector
352
- } ;
353
-
354
- return new FindOperatorsUnordered ( this ) ;
355
- } ;
356
-
357
- Object . defineProperty ( UnorderedBulkOperation . prototype , 'length' , {
358
- enumerable : true ,
359
- get : function ( ) {
360
- return this . s . currentIndex ;
361
- }
362
- } ) ;
363
-
364
- UnorderedBulkOperation . prototype . raw = function ( op ) {
365
- var key = Object . keys ( op ) [ 0 ] ;
366
-
367
- // Set up the force server object id
368
- var forceServerObjectId =
369
- typeof this . s . options . forceServerObjectId === 'boolean'
370
- ? this . s . options . forceServerObjectId
371
- : this . s . collection . s . db . options . forceServerObjectId ;
372
-
373
- // Update operations
374
- if (
375
- ( op . updateOne && op . updateOne . q ) ||
376
- ( op . updateMany && op . updateMany . q ) ||
377
- ( op . replaceOne && op . replaceOne . q )
378
- ) {
379
- op [ key ] . multi = op . updateOne || op . replaceOne ? false : true ;
380
- return addToOperationsList ( this , common . UPDATE , op [ key ] ) ;
381
- }
382
-
383
- // Crud spec update format
384
- if ( op . updateOne || op . updateMany || op . replaceOne ) {
385
- var multi = op . updateOne || op . replaceOne ? false : true ;
386
- var operation = { q : op [ key ] . filter , u : op [ key ] . update || op [ key ] . replacement , multi : multi } ;
387
- if ( op [ key ] . upsert ) operation . upsert = true ;
388
- if ( op [ key ] . arrayFilters ) operation . arrayFilters = op [ key ] . arrayFilters ;
389
- return addToOperationsList ( this , common . UPDATE , operation ) ;
390
- }
391
-
392
- // Remove operations
393
- if (
394
- op . removeOne ||
395
- op . removeMany ||
396
- ( op . deleteOne && op . deleteOne . q ) ||
397
- ( op . deleteMany && op . deleteMany . q )
398
- ) {
399
- op [ key ] . limit = op . removeOne ? 1 : 0 ;
400
- return addToOperationsList ( this , common . REMOVE , op [ key ] ) ;
401
- }
402
-
403
- // Crud spec delete operations, less efficient
404
- if ( op . deleteOne || op . deleteMany ) {
405
- var limit = op . deleteOne ? 1 : 0 ;
406
- operation = { q : op [ key ] . filter , limit : limit } ;
407
- return addToOperationsList ( this , common . REMOVE , operation ) ;
408
- }
409
-
410
- // Insert operations
411
- if ( op . insertOne && op . insertOne . document == null ) {
412
- if ( forceServerObjectId !== true && op . insertOne . _id == null ) op . insertOne . _id = new ObjectID ( ) ;
413
- return addToOperationsList ( this , common . INSERT , op . insertOne ) ;
414
- } else if ( op . insertOne && op . insertOne . document ) {
415
- if ( forceServerObjectId !== true && op . insertOne . document . _id == null )
416
- op . insertOne . document . _id = new ObjectID ( ) ;
417
- return addToOperationsList ( this , common . INSERT , op . insertOne . document ) ;
418
- }
419
-
420
- if ( op . insertMany ) {
421
- for ( var i = 0 ; i < op . insertMany . length ; i ++ ) {
422
- if ( forceServerObjectId !== true && op . insertMany [ i ] . _id == null )
423
- op . insertMany [ i ] . _id = new ObjectID ( ) ;
424
- addToOperationsList ( this , common . INSERT , op . insertMany [ i ] ) ;
425
- }
426
-
427
- return ;
428
- }
429
-
430
- // No valid type of operation
431
- throw toError (
432
- 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'
433
- ) ;
434
- } ;
435
-
436
- //
437
- // Execute the command
438
- var executeBatch = function ( self , batch , options , callback ) {
439
- var finalOptions = Object . assign ( { ordered : false } , options ) ;
440
- if ( self . s . writeConcern != null ) {
441
- finalOptions . writeConcern = self . s . writeConcern ;
442
- }
443
-
444
- if ( finalOptions . bypassDocumentValidation !== true ) {
445
- delete finalOptions . bypassDocumentValidation ;
446
- }
447
-
448
- var resultHandler = function ( err , result ) {
141
+ function executeBatch ( bulkOperation , batch , options , callback ) {
142
+ function resultHandler ( err , result ) {
449
143
// Error is a driver related error not a bulk op error, terminate
450
144
if ( ( ( err && err . driver ) || ( err && err . message ) ) && ! ( err instanceof MongoWriteConcernError ) ) {
451
145
return handleCallback ( callback , err ) ;
@@ -454,85 +148,30 @@ var executeBatch = function(self, batch, options, callback) {
454
148
// If we have and error
455
149
if ( err ) err . ok = 0 ;
456
150
if ( err instanceof MongoWriteConcernError ) {
457
- return handleMongoWriteConcernError ( batch , self . s . bulkResult , false , err , callback ) ;
151
+ return handleMongoWriteConcernError ( batch , bulkOperation . s . bulkResult , false , err , callback ) ;
458
152
}
459
- handleCallback ( callback , null , mergeBatchResults ( false , batch , self . s . bulkResult , err , result ) ) ;
460
- } ;
461
-
462
- // Set an operationIf if provided
463
- if ( self . operationId ) {
464
- resultHandler . operationId = self . operationId ;
465
- }
466
-
467
- // Serialize functions
468
- if ( self . s . options . serializeFunctions ) {
469
- finalOptions . serializeFunctions = true ;
153
+ handleCallback (
154
+ callback ,
155
+ null ,
156
+ mergeBatchResults ( false , batch , bulkOperation . s . bulkResult , err , result )
157
+ ) ;
470
158
}
471
159
472
- // Ignore undefined
473
- if ( self . s . options . ignoreUndefined ) {
474
- finalOptions . ignoreUndefined = true ;
475
- }
160
+ bulkOperation . finalOptionsHandler ( { options, batch, resultHandler } , callback ) ;
161
+ }
476
162
477
- // Is the bypassDocumentValidation options specific
478
- if ( self . s . bypassDocumentValidation === true ) {
479
- finalOptions . bypassDocumentValidation = true ;
480
- }
481
-
482
- // Is the checkKeys option disabled
483
- if ( self . s . checkKeys === false ) {
484
- finalOptions . checkKeys = false ;
485
- }
486
-
487
- if ( finalOptions . retryWrites ) {
488
- if ( batch . batchType === common . UPDATE ) {
489
- finalOptions . retryWrites = finalOptions . retryWrites && ! batch . operations . some ( op => op . multi ) ;
490
- }
491
-
492
- if ( batch . batchType === common . REMOVE ) {
493
- finalOptions . retryWrites =
494
- finalOptions . retryWrites && ! batch . operations . some ( op => op . limit === 0 ) ;
495
- }
496
- }
497
-
498
- try {
499
- if ( batch . batchType === common . INSERT ) {
500
- self . s . topology . insert (
501
- self . s . collection . namespace ,
502
- batch . operations ,
503
- finalOptions ,
504
- resultHandler
505
- ) ;
506
- } else if ( batch . batchType === common . UPDATE ) {
507
- self . s . topology . update (
508
- self . s . collection . namespace ,
509
- batch . operations ,
510
- finalOptions ,
511
- resultHandler
512
- ) ;
513
- } else if ( batch . batchType === common . REMOVE ) {
514
- self . s . topology . remove (
515
- self . s . collection . namespace ,
516
- batch . operations ,
517
- finalOptions ,
518
- resultHandler
519
- ) ;
520
- }
521
- } catch ( err ) {
522
- // Force top level error
523
- err . ok = 0 ;
524
- // Merge top level error and return
525
- handleCallback ( callback , null , mergeBatchResults ( false , batch , self . s . bulkResult , err , null ) ) ;
526
- }
527
- } ;
528
-
529
- //
530
- // Execute all the commands
531
- var executeBatches = function ( self , options , callback ) {
532
- var numberOfCommandsToExecute = self . s . batches . length ;
163
+ /**
164
+ * Execute all the commands
165
+ *
166
+ * @param {UnorderedBulkOperation } bulkOperation
167
+ * @param {object } options
168
+ * @param {function } callback
169
+ */
170
+ function executeBatches ( bulkOperation , options , callback ) {
171
+ let numberOfCommandsToExecute = bulkOperation . s . batches . length ;
533
172
// Execute over all the batches
534
- for ( var i = 0 ; i < self . s . batches . length ; i ++ ) {
535
- executeBatch ( self , self . s . batches [ i ] , options , function ( err ) {
173
+ for ( let i = 0 ; i < bulkOperation . s . batches . length ; i ++ ) {
174
+ executeBatch ( bulkOperation , bulkOperation . s . batches [ i ] , options , function ( err ) {
536
175
// Count down the number of commands left to execute
537
176
numberOfCommandsToExecute = numberOfCommandsToExecute - 1 ;
538
177
@@ -541,102 +180,22 @@ var executeBatches = function(self, options, callback) {
541
180
// Driver level error
542
181
if ( err ) return handleCallback ( callback , err ) ;
543
182
544
- const writeResult = new BulkWriteResult ( self . s . bulkResult ) ;
545
- if ( self . s . bulkResult . writeErrors . length > 0 ) {
546
- if ( self . s . bulkResult . writeErrors . length === 1 ) {
547
- return handleCallback (
548
- callback ,
549
- new BulkWriteError ( toError ( self . s . bulkResult . writeErrors [ 0 ] ) , writeResult ) ,
550
- null
551
- ) ;
552
- }
553
-
554
- return handleCallback (
555
- callback ,
556
- new BulkWriteError (
557
- toError ( {
558
- message : 'write operation failed' ,
559
- code : self . s . bulkResult . writeErrors [ 0 ] . code ,
560
- writeErrors : self . s . bulkResult . writeErrors
561
- } ) ,
562
- writeResult
563
- ) ,
564
- null
565
- ) ;
566
- } else if ( writeResult . getWriteConcernError ( ) ) {
567
- return handleCallback (
568
- callback ,
569
- new BulkWriteError ( toError ( writeResult . getWriteConcernError ( ) ) , writeResult ) ,
570
- null
571
- ) ;
572
- }
183
+ const writeResult = new BulkWriteResult ( bulkOperation . s . bulkResult ) ;
184
+ if ( bulkOperation . handleWriteError ( callback , writeResult ) ) return ;
573
185
574
186
return handleCallback ( callback , null , writeResult ) ;
575
187
}
576
188
} ) ;
577
189
}
578
- } ;
579
-
580
- /**
581
- * The callback format for results
582
- * @callback UnorderedBulkOperation~resultCallback
583
- * @param {MongoError } error An error instance representing the error during the execution.
584
- * @param {BulkWriteResult } result The bulk write result.
585
- */
586
-
587
- /**
588
- * Execute the ordered bulk operation
589
- *
590
- * @method
591
- * @param {object } [options] Optional settings.
592
- * @param {(number|string) } [options.w] The write concern.
593
- * @param {number } [options.wtimeout] The write concern timeout.
594
- * @param {boolean } [options.j=false] Specify a journal write concern.
595
- * @param {boolean } [options.fsync=false] Specify a file sync write concern.
596
- * @param {UnorderedBulkOperation~resultCallback } [callback] The result callback
597
- * @throws {MongoError }
598
- * @return {Promise } returns Promise if no callback passed
599
- */
600
- UnorderedBulkOperation . prototype . execute = function ( _writeConcern , options , callback ) {
601
- if ( typeof options === 'function' ) ( callback = options ) , ( options = { } ) ;
602
- options = options || { } ;
603
-
604
- if ( this . s . executed ) {
605
- var executedError = toError ( 'batch cannot be re-executed' ) ;
606
- return typeof callback === 'function'
607
- ? callback ( executedError , null )
608
- : this . s . promiseLibrary . reject ( executedError ) ;
609
- }
610
-
611
- if ( typeof _writeConcern === 'function' ) {
612
- callback = _writeConcern ;
613
- } else if ( _writeConcern && typeof _writeConcern === 'object' ) {
614
- this . s . writeConcern = _writeConcern ;
615
- }
616
-
617
- // If we have current batch
618
- if ( this . s . currentInsertBatch ) this . s . batches . push ( this . s . currentInsertBatch ) ;
619
- if ( this . s . currentUpdateBatch ) this . s . batches . push ( this . s . currentUpdateBatch ) ;
620
- if ( this . s . currentRemoveBatch ) this . s . batches . push ( this . s . currentRemoveBatch ) ;
621
-
622
- // If we have no operations in the bulk raise an error
623
- if ( this . s . batches . length === 0 ) {
624
- var emptyBatchError = toError ( 'Invalid Operation, no operations specified' ) ;
625
- return typeof callback === 'function'
626
- ? callback ( emptyBatchError , null )
627
- : this . s . promiseLibrary . reject ( emptyBatchError ) ;
628
- }
629
-
630
- return executeOperation ( this . s . topology , executeBatches , [ this , options , callback ] ) ;
631
- } ;
190
+ }
632
191
633
192
/**
634
193
* Returns an unordered batch object
635
194
* @ignore
636
195
*/
637
- var initializeUnorderedBulkOp = function ( topology , collection , options ) {
196
+ function initializeUnorderedBulkOp ( topology , collection , options ) {
638
197
return new UnorderedBulkOperation ( topology , collection , options ) ;
639
- } ;
198
+ }
640
199
641
200
initializeUnorderedBulkOp . UnorderedBulkOperation = UnorderedBulkOperation ;
642
201
module . exports = initializeUnorderedBulkOp ;
0 commit comments