common.js
34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
'use strict';
const Long = require('../core').BSON.Long;
const MongoError = require('../core').MongoError;
const ObjectID = require('../core').BSON.ObjectID;
const BSON = require('../core').BSON;
const MongoWriteConcernError = require('../core').MongoWriteConcernError;
const toError = require('../utils').toError;
const handleCallback = require('../utils').handleCallback;
const applyRetryableWrites = require('../utils').applyRetryableWrites;
const applyWriteConcern = require('../utils').applyWriteConcern;
const executeLegacyOperation = require('../utils').executeLegacyOperation;
const isPromiseLike = require('../utils').isPromiseLike;
// Error codes
const WRITE_CONCERN_ERROR = 64;
// Insert types
const INSERT = 1;
const UPDATE = 2;
const REMOVE = 3;
const bson = new BSON([
BSON.Binary,
BSON.Code,
BSON.DBRef,
BSON.Decimal128,
BSON.Double,
BSON.Int32,
BSON.Long,
BSON.Map,
BSON.MaxKey,
BSON.MinKey,
BSON.ObjectId,
BSON.BSONRegExp,
BSON.Symbol,
BSON.Timestamp
]);
/**
* Keeps the state of a unordered batch so we can rewrite the results
* correctly after command execution
* @ignore
*/
class Batch {
constructor(batchType, originalZeroIndex) {
this.originalZeroIndex = originalZeroIndex;
this.currentIndex = 0;
this.originalIndexes = [];
this.batchType = batchType;
this.operations = [];
this.size = 0;
this.sizeBytes = 0;
}
}
/**
* @classdesc
* The result of a bulk write.
*/
class BulkWriteResult {
/**
* Create a new BulkWriteResult instance
*
* **NOTE:** Internal Type, do not instantiate directly
*/
constructor(bulkResult) {
this.result = bulkResult;
}
/**
* Evaluates to true if the bulk operation correctly executes
* @type {boolean}
*/
get ok() {
return this.result.ok;
}
/**
* The number of inserted documents
* @type {number}
*/
get nInserted() {
return this.result.nInserted;
}
/**
* Number of upserted documents
* @type {number}
*/
get nUpserted() {
return this.result.nUpserted;
}
/**
* Number of matched documents
* @type {number}
*/
get nMatched() {
return this.result.nMatched;
}
/**
* Number of documents updated physically on disk
* @type {number}
*/
get nModified() {
return this.result.nModified;
}
/**
* Number of removed documents
* @type {number}
*/
get nRemoved() {
return this.result.nRemoved;
}
/**
* Returns an array of all inserted ids
*
* @return {object[]}
*/
getInsertedIds() {
return this.result.insertedIds;
}
/**
* Returns an array of all upserted ids
*
* @return {object[]}
*/
getUpsertedIds() {
return this.result.upserted;
}
/**
* Returns the upserted id at the given index
*
* @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index
* @return {object}
*/
getUpsertedIdAt(index) {
return this.result.upserted[index];
}
/**
* Returns raw internal result
*
* @return {object}
*/
getRawResponse() {
return this.result;
}
/**
* Returns true if the bulk operation contains a write error
*
* @return {boolean}
*/
hasWriteErrors() {
return this.result.writeErrors.length > 0;
}
/**
* Returns the number of write errors off the bulk operation
*
* @return {number}
*/
getWriteErrorCount() {
return this.result.writeErrors.length;
}
/**
* Returns a specific write error object
*
* @param {number} index of the write error to return, returns null if there is no result for passed in index
* @return {WriteError}
*/
getWriteErrorAt(index) {
if (index < this.result.writeErrors.length) {
return this.result.writeErrors[index];
}
return null;
}
/**
* Retrieve all write errors
*
* @return {WriteError[]}
*/
getWriteErrors() {
return this.result.writeErrors;
}
/**
* Retrieve lastOp if available
*
* @return {object}
*/
getLastOp() {
return this.result.lastOp;
}
/**
* Retrieve the write concern error if any
*
* @return {WriteConcernError}
*/
getWriteConcernError() {
if (this.result.writeConcernErrors.length === 0) {
return null;
} else if (this.result.writeConcernErrors.length === 1) {
// Return the error
return this.result.writeConcernErrors[0];
} else {
// Combine the errors
let errmsg = '';
for (let i = 0; i < this.result.writeConcernErrors.length; i++) {
const err = this.result.writeConcernErrors[i];
errmsg = errmsg + err.errmsg;
// TODO: Something better
if (i === 0) errmsg = errmsg + ' and ';
}
return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR });
}
}
/**
* @return {object}
*/
toJSON() {
return this.result;
}
/**
* @return {string}
*/
toString() {
return `BulkWriteResult(${this.toJSON(this.result)})`;
}
/**
* @return {boolean}
*/
isOk() {
return this.result.ok === 1;
}
}
/**
* @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation.
*/
class WriteConcernError {
/**
* Create a new WriteConcernError instance
*
* **NOTE:** Internal Type, do not instantiate directly
*/
constructor(err) {
this.err = err;
}
/**
* Write concern error code.
* @type {number}
*/
get code() {
return this.err.code;
}
/**
* Write concern error message.
* @type {string}
*/
get errmsg() {
return this.err.errmsg;
}
/**
* @return {object}
*/
toJSON() {
return { code: this.err.code, errmsg: this.err.errmsg };
}
/**
* @return {string}
*/
toString() {
return `WriteConcernError(${this.err.errmsg})`;
}
}
/**
* @classdesc An error that occurred during a BulkWrite on the server.
*/
class WriteError {
/**
* Create a new WriteError instance
*
* **NOTE:** Internal Type, do not instantiate directly
*/
constructor(err) {
this.err = err;
}
/**
* WriteError code.
* @type {number}
*/
get code() {
return this.err.code;
}
/**
* WriteError original bulk operation index.
* @type {number}
*/
get index() {
return this.err.index;
}
/**
* WriteError message.
* @type {string}
*/
get errmsg() {
return this.err.errmsg;
}
/**
* Returns the underlying operation that caused the error
* @return {object}
*/
getOperation() {
return this.err.op;
}
/**
* @return {object}
*/
toJSON() {
return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
}
/**
* @return {string}
*/
toString() {
return `WriteError(${JSON.stringify(this.toJSON())})`;
}
}
/**
* Merges results into shared data structure
* @ignore
*/
function mergeBatchResults(batch, bulkResult, err, result) {
// If we have an error set the result to be the err object
if (err) {
result = err;
} else if (result && result.result) {
result = result.result;
} else if (result == null) {
return;
}
// Do we have a top level error stop processing and return
if (result.ok === 0 && bulkResult.ok === 1) {
bulkResult.ok = 0;
const writeError = {
index: 0,
code: result.code || 0,
errmsg: result.message,
op: batch.operations[0]
};
bulkResult.writeErrors.push(new WriteError(writeError));
return;
} else if (result.ok === 0 && bulkResult.ok === 0) {
return;
}
// Deal with opTime if available
if (result.opTime || result.lastOp) {
const opTime = result.lastOp || result.opTime;
let lastOpTS = null;
let lastOpT = null;
// We have a time stamp
if (opTime && opTime._bsontype === 'Timestamp') {
if (bulkResult.lastOp == null) {
bulkResult.lastOp = opTime;
} else if (opTime.greaterThan(bulkResult.lastOp)) {
bulkResult.lastOp = opTime;
}
} else {
// Existing TS
if (bulkResult.lastOp) {
lastOpTS =
typeof bulkResult.lastOp.ts === 'number'
? Long.fromNumber(bulkResult.lastOp.ts)
: bulkResult.lastOp.ts;
lastOpT =
typeof bulkResult.lastOp.t === 'number'
? Long.fromNumber(bulkResult.lastOp.t)
: bulkResult.lastOp.t;
}
// Current OpTime TS
const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts;
const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t;
// Compare the opTime's
if (bulkResult.lastOp == null) {
bulkResult.lastOp = opTime;
} else if (opTimeTS.greaterThan(lastOpTS)) {
bulkResult.lastOp = opTime;
} else if (opTimeTS.equals(lastOpTS)) {
if (opTimeT.greaterThan(lastOpT)) {
bulkResult.lastOp = opTime;
}
}
}
}
// If we have an insert Batch type
if (batch.batchType === INSERT && result.n) {
bulkResult.nInserted = bulkResult.nInserted + result.n;
}
// If we have an insert Batch type
if (batch.batchType === REMOVE && result.n) {
bulkResult.nRemoved = bulkResult.nRemoved + result.n;
}
let nUpserted = 0;
// We have an array of upserted values, we need to rewrite the indexes
if (Array.isArray(result.upserted)) {
nUpserted = result.upserted.length;
for (let i = 0; i < result.upserted.length; i++) {
bulkResult.upserted.push({
index: result.upserted[i].index + batch.originalZeroIndex,
_id: result.upserted[i]._id
});
}
} else if (result.upserted) {
nUpserted = 1;
bulkResult.upserted.push({
index: batch.originalZeroIndex,
_id: result.upserted
});
}
// If we have an update Batch type
if (batch.batchType === UPDATE && result.n) {
const nModified = result.nModified;
bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
if (typeof nModified === 'number') {
bulkResult.nModified = bulkResult.nModified + nModified;
} else {
bulkResult.nModified = null;
}
}
if (Array.isArray(result.writeErrors)) {
for (let i = 0; i < result.writeErrors.length; i++) {
const writeError = {
index: batch.originalIndexes[i],
code: result.writeErrors[i].code,
errmsg: result.writeErrors[i].errmsg,
op: batch.operations[result.writeErrors[i].index]
};
bulkResult.writeErrors.push(new WriteError(writeError));
}
}
if (result.writeConcernError) {
bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
}
}
function executeCommands(bulkOperation, options, callback) {
if (bulkOperation.s.batches.length === 0) {
return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult));
}
const batch = bulkOperation.s.batches.shift();
function resultHandler(err, result) {
// Error is a driver related error not a bulk op error, terminate
if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
return handleCallback(callback, err);
}
// If we have and error
if (err) err.ok = 0;
if (err instanceof MongoWriteConcernError) {
return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback);
}
// Merge the results together
const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result);
if (mergeResult != null) {
return handleCallback(callback, null, writeResult);
}
if (bulkOperation.handleWriteError(callback, writeResult)) return;
// Execute the next command in line
executeCommands(bulkOperation, options, callback);
}
bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
/**
* handles write concern error
*
* @ignore
* @param {object} batch
* @param {object} bulkResult
* @param {boolean} ordered
* @param {WriteConcernError} err
* @param {function} callback
*/
function handleMongoWriteConcernError(batch, bulkResult, err, callback) {
mergeBatchResults(batch, bulkResult, null, err.result);
const wrappedWriteConcernError = new WriteConcernError({
errmsg: err.result.writeConcernError.errmsg,
code: err.result.writeConcernError.result
});
return handleCallback(
callback,
new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
null
);
}
/**
* @classdesc An error indicating an unsuccessful Bulk Write
*/
class BulkWriteError extends MongoError {
/**
* Creates a new BulkWriteError
*
* @param {Error|string|object} message The error message
* @param {BulkWriteResult} result The result of the bulk write operation
* @extends {MongoError}
*/
constructor(error, result) {
const message = error.err || error.errmsg || error.errMessage || error;
super(message);
Object.assign(this, error);
this.name = 'BulkWriteError';
this.result = result;
}
}
/**
* @classdesc A builder object that is returned from {@link BulkOperationBase#find}.
* Is used to build a write operation that involves a query filter.
*/
class FindOperators {
/**
* Creates a new FindOperators object.
*
* **NOTE:** Internal Type, do not instantiate directly
* @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation
*/
constructor(bulkOperation) {
this.s = bulkOperation.s;
}
/**
* Add a multiple update operation to the bulk operation
*
* @method
* @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}
* @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
* @throws {MongoError} If operation cannot be added to bulk write
* @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
*/
update(updateDocument) {
// Perform upsert
const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
// Establish the update command
const document = {
q: this.s.currentOp.selector,
u: updateDocument,
multi: true,
upsert: upsert
};
if (updateDocument.hint) {
document.hint = updateDocument.hint;
}
// Clear out current Op
this.s.currentOp = null;
return this.s.options.addToOperationsList(this, UPDATE, document);
}
/**
* Add a single update operation to the bulk operation
*
* @method
* @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation}
* @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
* @throws {MongoError} If operation cannot be added to bulk write
* @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
*/
updateOne(updateDocument) {
// Perform upsert
const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false;
// Establish the update command
const document = {
q: this.s.currentOp.selector,
u: updateDocument,
multi: false,
upsert: upsert
};
if (updateDocument.hint) {
document.hint = updateDocument.hint;
}
// Clear out current Op
this.s.currentOp = null;
return this.s.options.addToOperationsList(this, UPDATE, document);
}
/**
* Add a replace one operation to the bulk operation
*
* @method
* @param {object} updateDocument the new document to replace the existing one with
* @throws {MongoError} If operation cannot be added to bulk write
* @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
*/
replaceOne(updateDocument) {
this.updateOne(updateDocument);
}
/**
* Upsert modifier for update bulk operation, noting that this operation is an upsert.
*
* @method
* @throws {MongoError} If operation cannot be added to bulk write
* @return {FindOperators} reference to self
*/
upsert() {
this.s.currentOp.upsert = true;
return this;
}
/**
* Add a delete one operation to the bulk operation
*
* @method
* @throws {MongoError} If operation cannot be added to bulk write
* @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
*/
deleteOne() {
// Establish the update command
const document = {
q: this.s.currentOp.selector,
limit: 1
};
// Clear out current Op
this.s.currentOp = null;
return this.s.options.addToOperationsList(this, REMOVE, document);
}
/**
* Add a delete many operation to the bulk operation
*
* @method
* @throws {MongoError} If operation cannot be added to bulk write
* @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation
*/
delete() {
// Establish the update command
const document = {
q: this.s.currentOp.selector,
limit: 0
};
// Clear out current Op
this.s.currentOp = null;
return this.s.options.addToOperationsList(this, REMOVE, document);
}
/**
* backwards compatability for deleteOne
*/
removeOne() {
return this.deleteOne();
}
/**
* backwards compatability for delete
*/
remove() {
return this.delete();
}
}
/**
* @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation
*
* **NOTE:** Internal Type, do not instantiate directly
*/
class BulkOperationBase {
/**
* Create a new OrderedBulkOperation or UnorderedBulkOperation instance
* @property {number} length Get the number of operations in the bulk.
*/
constructor(topology, collection, options, isOrdered) {
// determine whether bulkOperation is ordered or unordered
this.isOrdered = isOrdered;
options = options == null ? {} : options;
// TODO Bring from driver information in isMaster
// Get the namespace for the write operations
const namespace = collection.s.namespace;
// Used to mark operation as executed
const executed = false;
// Current item
const currentOp = null;
// Handle to the bson serializer, used to calculate running sizes
const bson = topology.bson;
// Set max byte size
const isMaster = topology.lastIsMaster();
const maxBatchSizeBytes =
isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16;
const maxWriteBatchSize =
isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000;
// Calculates the largest possible size of an Array key, represented as a BSON string
// element. This calculation:
// 1 byte for BSON type
// # of bytes = length of (string representation of (maxWriteBatchSize - 1))
// + 1 bytes for null terminator
const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
// Final options for retryable writes and write concern
let finalOptions = Object.assign({}, options);
finalOptions = applyRetryableWrites(finalOptions, collection.s.db);
finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options);
const writeConcern = finalOptions.writeConcern;
// Get the promiseLibrary
const promiseLibrary = options.promiseLibrary || Promise;
// Final results
const bulkResult = {
ok: 1,
writeErrors: [],
writeConcernErrors: [],
insertedIds: [],
nInserted: 0,
nUpserted: 0,
nMatched: 0,
nModified: 0,
nRemoved: 0,
upserted: []
};
// Internal state
this.s = {
// Final result
bulkResult: bulkResult,
// Current batch state
currentBatch: null,
currentIndex: 0,
// ordered specific
currentBatchSize: 0,
currentBatchSizeBytes: 0,
// unordered specific
currentInsertBatch: null,
currentUpdateBatch: null,
currentRemoveBatch: null,
batches: [],
// Write concern
writeConcern: writeConcern,
// Max batch size options
maxBatchSizeBytes: maxBatchSizeBytes,
maxWriteBatchSize: maxWriteBatchSize,
maxKeySize,
// Namespace
namespace: namespace,
// BSON
bson: bson,
// Topology
topology: topology,
// Options
options: finalOptions,
// Current operation
currentOp: currentOp,
// Executed
executed: executed,
// Collection
collection: collection,
// Promise Library
promiseLibrary: promiseLibrary,
// Fundamental error
err: null,
// check keys
checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true
};
// bypass Validation
if (options.bypassDocumentValidation === true) {
this.s.bypassDocumentValidation = true;
}
}
/**
* Add a single insert document to the bulk operation
*
* @param {object} document the document to insert
* @throws {MongoError}
* @return {BulkOperationBase} A reference to self
*
* @example
* const bulkOp = collection.initializeOrderedBulkOp();
* // Adds three inserts to the bulkOp.
* bulkOp
* .insert({ a: 1 })
* .insert({ b: 2 })
* .insert({ c: 3 });
* await bulkOp.execute();
*/
insert(document) {
if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null)
document._id = new ObjectID();
return this.s.options.addToOperationsList(this, INSERT, document);
}
/**
* Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
* Returns a builder object used to complete the definition of the operation.
*
* @method
* @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation}
* @throws {MongoError} if a selector is not specified
* @return {FindOperators} A helper object with which the write operation can be defined.
*
* @example
* const bulkOp = collection.initializeOrderedBulkOp();
*
* // Add an updateOne to the bulkOp
* bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
*
* // Add an updateMany to the bulkOp
* bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
*
* // Add an upsert
* bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
*
* // Add a deletion
* bulkOp.find({ g: 7 }).deleteOne();
*
* // Add a multi deletion
* bulkOp.find({ h: 8 }).delete();
*
* // Add a replaceOne
* bulkOp.find({ i: 9 }).replaceOne({ j: 10 });
*
* // Update using a pipeline (requires Mongodb 4.2 or higher)
* bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
* { $set: { total: { $sum: [ '$y', '$z' ] } } }
* ]);
*
* // All of the ops will now be executed
* await bulkOp.execute();
*/
find(selector) {
if (!selector) {
throw toError('Bulk find operation must specify a selector');
}
// Save a current selector
this.s.currentOp = {
selector: selector
};
return new FindOperators(this);
}
/**
* Specifies a raw operation to perform in the bulk write.
*
* @method
* @param {object} op The raw operation to perform.
* @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information.
* @return {BulkOperationBase} A reference to self
*/
raw(op) {
const key = Object.keys(op)[0];
// Set up the force server object id
const forceServerObjectId =
typeof this.s.options.forceServerObjectId === 'boolean'
? this.s.options.forceServerObjectId
: this.s.collection.s.db.options.forceServerObjectId;
// Update operations
if (
(op.updateOne && op.updateOne.q) ||
(op.updateMany && op.updateMany.q) ||
(op.replaceOne && op.replaceOne.q)
) {
op[key].multi = op.updateOne || op.replaceOne ? false : true;
return this.s.options.addToOperationsList(this, UPDATE, op[key]);
}
// Crud spec update format
if (op.updateOne || op.updateMany || op.replaceOne) {
const multi = op.updateOne || op.replaceOne ? false : true;
const operation = {
q: op[key].filter,
u: op[key].update || op[key].replacement,
multi: multi
};
if (op[key].hint) {
operation.hint = op[key].hint;
}
if (this.isOrdered) {
operation.upsert = op[key].upsert ? true : false;
if (op.collation) operation.collation = op.collation;
} else {
if (op[key].upsert) operation.upsert = true;
}
if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters;
return this.s.options.addToOperationsList(this, UPDATE, operation);
}
// Remove operations
if (
op.removeOne ||
op.removeMany ||
(op.deleteOne && op.deleteOne.q) ||
(op.deleteMany && op.deleteMany.q)
) {
op[key].limit = op.removeOne ? 1 : 0;
return this.s.options.addToOperationsList(this, REMOVE, op[key]);
}
// Crud spec delete operations, less efficient
if (op.deleteOne || op.deleteMany) {
const limit = op.deleteOne ? 1 : 0;
const operation = { q: op[key].filter, limit: limit };
if (this.isOrdered) {
if (op.collation) operation.collation = op.collation;
}
return this.s.options.addToOperationsList(this, REMOVE, operation);
}
// Insert operations
if (op.insertOne && op.insertOne.document == null) {
if (forceServerObjectId !== true && op.insertOne._id == null)
op.insertOne._id = new ObjectID();
return this.s.options.addToOperationsList(this, INSERT, op.insertOne);
} else if (op.insertOne && op.insertOne.document) {
if (forceServerObjectId !== true && op.insertOne.document._id == null)
op.insertOne.document._id = new ObjectID();
return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document);
}
if (op.insertMany) {
for (let i = 0; i < op.insertMany.length; i++) {
if (forceServerObjectId !== true && op.insertMany[i]._id == null)
op.insertMany[i]._id = new ObjectID();
this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]);
}
return;
}
// No valid type of operation
throw toError(
'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany'
);
}
/**
* helper function to assist with promiseOrCallback behavior
* @ignore
* @param {*} err
* @param {*} callback
*/
_handleEarlyError(err, callback) {
if (typeof callback === 'function') {
callback(err, null);
return;
}
return this.s.promiseLibrary.reject(err);
}
/**
* An internal helper method. Do not invoke directly. Will be going away in the future
*
* @ignore
* @method
* @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation
* @param {object} writeConcern
* @param {object} options
* @param {function} callback
*/
bulkExecute(_writeConcern, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
if (typeof _writeConcern === 'function') {
callback = _writeConcern;
} else if (_writeConcern && typeof _writeConcern === 'object') {
this.s.writeConcern = _writeConcern;
}
if (this.s.executed) {
const executedError = toError('batch cannot be re-executed');
return this._handleEarlyError(executedError, callback);
}
// If we have current batch
if (this.isOrdered) {
if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
} else {
if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
}
// If we have no operations in the bulk raise an error
if (this.s.batches.length === 0) {
const emptyBatchError = toError('Invalid Operation, no operations specified');
return this._handleEarlyError(emptyBatchError, callback);
}
return { options, callback };
}
/**
* The callback format for results
* @callback BulkOperationBase~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {BulkWriteResult} result The bulk write result.
*/
/**
* Execute the bulk operation
*
* @method
* @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options.
* @param {object} [options] Optional settings.
* @param {(number|string)} [options.w] The write concern.
* @param {number} [options.wtimeout] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.fsync=false] Specify a file sync write concern.
* @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors
* @throws {MongoError} Throws error if the bulk object has already been executed
* @throws {MongoError} Throws error if the bulk object does not have any operations
* @return {Promise|void} returns Promise if no callback passed
*/
execute(_writeConcern, options, callback) {
const ret = this.bulkExecute(_writeConcern, options, callback);
if (!ret || isPromiseLike(ret)) {
return ret;
}
options = ret.options;
callback = ret.callback;
return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]);
}
/**
* Handles final options before executing command
*
* An internal method. Do not invoke. Will not be accessible in the future
*
* @ignore
* @param {object} config
* @param {object} config.options
* @param {number} config.batch
* @param {function} config.resultHandler
* @param {function} callback
*/
finalOptionsHandler(config, callback) {
const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options);
if (this.s.writeConcern != null) {
finalOptions.writeConcern = this.s.writeConcern;
}
if (finalOptions.bypassDocumentValidation !== true) {
delete finalOptions.bypassDocumentValidation;
}
// Set an operationIf if provided
if (this.operationId) {
config.resultHandler.operationId = this.operationId;
}
// Serialize functions
if (this.s.options.serializeFunctions) {
finalOptions.serializeFunctions = true;
}
// Ignore undefined
if (this.s.options.ignoreUndefined) {
finalOptions.ignoreUndefined = true;
}
// Is the bypassDocumentValidation options specific
if (this.s.bypassDocumentValidation === true) {
finalOptions.bypassDocumentValidation = true;
}
// Is the checkKeys option disabled
if (this.s.checkKeys === false) {
finalOptions.checkKeys = false;
}
if (finalOptions.retryWrites) {
if (config.batch.batchType === UPDATE) {
finalOptions.retryWrites =
finalOptions.retryWrites && !config.batch.operations.some(op => op.multi);
}
if (config.batch.batchType === REMOVE) {
finalOptions.retryWrites =
finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0);
}
}
try {
if (config.batch.batchType === INSERT) {
this.s.topology.insert(
this.s.namespace,
config.batch.operations,
finalOptions,
config.resultHandler
);
} else if (config.batch.batchType === UPDATE) {
this.s.topology.update(
this.s.namespace,
config.batch.operations,
finalOptions,
config.resultHandler
);
} else if (config.batch.batchType === REMOVE) {
this.s.topology.remove(
this.s.namespace,
config.batch.operations,
finalOptions,
config.resultHandler
);
}
} catch (err) {
// Force top level error
err.ok = 0;
// Merge top level error and return
handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null));
}
}
/**
* Handles the write error before executing commands
*
* An internal helper method. Do not invoke directly. Will be going away in the future
*
* @ignore
* @param {function} callback
* @param {BulkWriteResult} writeResult
* @param {class} self either OrderedBulkOperation or UnorderdBulkOperation
*/
handleWriteError(callback, writeResult) {
if (this.s.bulkResult.writeErrors.length > 0) {
if (this.s.bulkResult.writeErrors.length === 1) {
handleCallback(
callback,
new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult),
null
);
return true;
}
const msg = this.s.bulkResult.writeErrors[0].errmsg
? this.s.bulkResult.writeErrors[0].errmsg
: 'write operation failed';
handleCallback(
callback,
new BulkWriteError(
toError({
message: msg,
code: this.s.bulkResult.writeErrors[0].code,
writeErrors: this.s.bulkResult.writeErrors
}),
writeResult
),
null
);
return true;
} else if (writeResult.getWriteConcernError()) {
handleCallback(
callback,
new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult),
null
);
return true;
}
}
}
Object.defineProperty(BulkOperationBase.prototype, 'length', {
enumerable: true,
get: function() {
return this.s.currentIndex;
}
});
// Exports symbols
module.exports = {
Batch,
BulkOperationBase,
bson,
INSERT: INSERT,
UPDATE: UPDATE,
REMOVE: REMOVE,
BulkWriteError
};