-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
mongo_driver.js
1595 lines (1383 loc) · 52.9 KB
/
mongo_driver.js
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
import { normalizeProjection } from "./mongo_utils";
/**
* Provide a synchronous Collection API using fibers, backed by
* MongoDB. This is only for use on the server, and mostly identical
* to the client API.
*
* NOTE: the public API methods must be run within a fiber. If you call
* these outside of a fiber they will explode!
*/
const path = require("path");
const util = require("util");
/** @type {import('mongodb')} */
var MongoDB = NpmModuleMongodb;
var Future = Npm.require('fibers/future');
import { DocFetcher } from "./doc_fetcher.js";
import {
ASYNC_CURSOR_METHODS,
getAsyncMethodName
} from "meteor/minimongo/constants";
MongoInternals = {};
MongoInternals.NpmModules = {
mongodb: {
version: NpmModuleMongodbVersion,
module: MongoDB
}
};
// Older version of what is now available via
// MongoInternals.NpmModules.mongodb.module. It was never documented, but
// people do use it.
// XXX COMPAT WITH 1.0.3.2
MongoInternals.NpmModule = MongoDB;
const FILE_ASSET_SUFFIX = 'Asset';
const ASSETS_FOLDER = 'assets';
const APP_FOLDER = 'app';
// This is used to add or remove EJSON from the beginning of everything nested
// inside an EJSON custom type. It should only be called on pure JSON!
var replaceNames = function (filter, thing) {
if (typeof thing === "object" && thing !== null) {
if (_.isArray(thing)) {
return _.map(thing, _.bind(replaceNames, null, filter));
}
var ret = {};
_.each(thing, function (value, key) {
ret[filter(key)] = replaceNames(filter, value);
});
return ret;
}
return thing;
};
// Ensure that EJSON.clone keeps a Timestamp as a Timestamp (instead of just
// doing a structural clone).
// XXX how ok is this? what if there are multiple copies of MongoDB loaded?
MongoDB.Timestamp.prototype.clone = function () {
// Timestamps should be immutable.
return this;
};
var makeMongoLegal = function (name) { return "EJSON" + name; };
var unmakeMongoLegal = function (name) { return name.substr(5); };
var replaceMongoAtomWithMeteor = function (document) {
if (document instanceof MongoDB.Binary) {
// for backwards compatibility
if (document.sub_type !== 0) {
return document;
}
var buffer = document.value(true);
return new Uint8Array(buffer);
}
if (document instanceof MongoDB.ObjectID) {
return new Mongo.ObjectID(document.toHexString());
}
if (document instanceof MongoDB.Decimal128) {
return Decimal(document.toString());
}
if (document["EJSON$type"] && document["EJSON$value"] && _.size(document) === 2) {
return EJSON.fromJSONValue(replaceNames(unmakeMongoLegal, document));
}
if (document instanceof MongoDB.Timestamp) {
// For now, the Meteor representation of a Mongo timestamp type (not a date!
// this is a weird internal thing used in the oplog!) is the same as the
// Mongo representation. We need to do this explicitly or else we would do a
// structural clone and lose the prototype.
return document;
}
return undefined;
};
var replaceMeteorAtomWithMongo = function (document) {
if (EJSON.isBinary(document)) {
// This does more copies than we'd like, but is necessary because
// MongoDB.BSON only looks like it takes a Uint8Array (and doesn't actually
// serialize it correctly).
return new MongoDB.Binary(Buffer.from(document));
}
if (document instanceof MongoDB.Binary) {
return document;
}
if (document instanceof Mongo.ObjectID) {
return new MongoDB.ObjectID(document.toHexString());
}
if (document instanceof MongoDB.Timestamp) {
// For now, the Meteor representation of a Mongo timestamp type (not a date!
// this is a weird internal thing used in the oplog!) is the same as the
// Mongo representation. We need to do this explicitly or else we would do a
// structural clone and lose the prototype.
return document;
}
if (document instanceof Decimal) {
return MongoDB.Decimal128.fromString(document.toString());
}
if (EJSON._isCustomType(document)) {
return replaceNames(makeMongoLegal, EJSON.toJSONValue(document));
}
// It is not ordinarily possible to stick dollar-sign keys into mongo
// so we don't bother checking for things that need escaping at this time.
return undefined;
};
var replaceTypes = function (document, atomTransformer) {
if (typeof document !== 'object' || document === null)
return document;
var replacedTopLevelAtom = atomTransformer(document);
if (replacedTopLevelAtom !== undefined)
return replacedTopLevelAtom;
var ret = document;
_.each(document, function (val, key) {
var valReplaced = replaceTypes(val, atomTransformer);
if (val !== valReplaced) {
// Lazy clone. Shallow copy.
if (ret === document)
ret = _.clone(document);
ret[key] = valReplaced;
}
});
return ret;
};
MongoConnection = function (url, options) {
var self = this;
options = options || {};
self._observeMultiplexers = {};
self._onFailoverHook = new Hook;
const userOptions = {
...(Mongo._connectionOptions || {}),
...(Meteor.settings?.packages?.mongo?.options || {})
};
var mongoOptions = Object.assign({
ignoreUndefined: true,
}, userOptions);
// Internally the oplog connections specify their own maxPoolSize
// which we don't want to overwrite with any user defined value
if (_.has(options, 'maxPoolSize')) {
// If we just set this for "server", replSet will override it. If we just
// set it for replSet, it will be ignored if we're not using a replSet.
mongoOptions.maxPoolSize = options.maxPoolSize;
}
if (_.has(options, 'minPoolSize')) {
mongoOptions.minPoolSize = options.minPoolSize;
}
// Transform options like "tlsCAFileAsset": "filename.pem" into
// "tlsCAFile": "/<fullpath>/filename.pem"
Object.entries(mongoOptions || {})
.filter(([key]) => key && key.endsWith(FILE_ASSET_SUFFIX))
.forEach(([key, value]) => {
const optionName = key.replace(FILE_ASSET_SUFFIX, '');
mongoOptions[optionName] = path.join(Assets.getServerDir(),
ASSETS_FOLDER, APP_FOLDER, value);
delete mongoOptions[key];
});
self.db = null;
self._oplogHandle = null;
self._docFetcher = null;
self.client = new MongoDB.MongoClient(url, mongoOptions);
self.db = self.client.db();
self.client.on('serverDescriptionChanged', Meteor.bindEnvironment(event => {
// When the connection is no longer against the primary node, execute all
// failover hooks. This is important for the driver as it has to re-pool the
// query when it happens.
if (
event.previousDescription.type !== 'RSPrimary' &&
event.newDescription.type === 'RSPrimary'
) {
self._onFailoverHook.each(callback => {
callback();
return true;
});
}
}));
if (options.oplogUrl && ! Package['disable-oplog']) {
self._oplogHandle = new OplogHandle(options.oplogUrl, self.db.databaseName);
self._docFetcher = new DocFetcher(self);
}
Promise.await(self.client.connect())
};
MongoConnection.prototype.close = function() {
var self = this;
if (! self.db)
throw Error("close called before Connection created?");
// XXX probably untested
var oplogHandle = self._oplogHandle;
self._oplogHandle = null;
if (oplogHandle)
oplogHandle.stop();
// Use Future.wrap so that errors get thrown. This happens to
// work even outside a fiber since the 'close' method is not
// actually asynchronous.
Future.wrap(_.bind(self.client.close, self.client))(true).wait();
};
MongoConnection.prototype._setOplogHandle = function(oplogHandle) {
this._oplogHandle = oplogHandle;
return this;
};
// Returns the Mongo Collection object; may yield.
MongoConnection.prototype.rawCollection = function (collectionName) {
var self = this;
if (! self.db)
throw Error("rawCollection called before Connection created?");
return self.db.collection(collectionName);
};
MongoConnection.prototype._createCappedCollection = function (
collectionName, byteSize, maxDocuments) {
var self = this;
if (! self.db)
throw Error("_createCappedCollection called before Connection created?");
var future = new Future();
self.db.createCollection(
collectionName,
{ capped: true, size: byteSize, max: maxDocuments },
future.resolver());
future.wait();
};
// This should be called synchronously with a write, to create a
// transaction on the current write fence, if any. After we can read
// the write, and after observers have been notified (or at least,
// after the observer notifiers have added themselves to the write
// fence), you should call 'committed()' on the object returned.
MongoConnection.prototype._maybeBeginWrite = function () {
var fence = DDPServer._CurrentWriteFence.get();
if (fence) {
return fence.beginWrite();
} else {
return {committed: function () {}};
}
};
// Internal interface: adds a callback which is called when the Mongo primary
// changes. Returns a stop handle.
MongoConnection.prototype._onFailover = function (callback) {
return this._onFailoverHook.register(callback);
};
//////////// Public API //////////
// The write methods block until the database has confirmed the write (it may
// not be replicated or stable on disk, but one server has confirmed it) if no
// callback is provided. If a callback is provided, then they call the callback
// when the write is confirmed. They return nothing on success, and raise an
// exception on failure.
//
// After making a write (with insert, update, remove), observers are
// notified asynchronously. If you want to receive a callback once all
// of the observer notifications have landed for your write, do the
// writes inside a write fence (set DDPServer._CurrentWriteFence to a new
// _WriteFence, and then set a callback on the write fence.)
//
// Since our execution environment is single-threaded, this is
// well-defined -- a write "has been made" if it's returned, and an
// observer "has been notified" if its callback has returned.
var writeCallback = function (write, refresh, callback) {
return function (err, result) {
if (! err) {
// XXX We don't have to run this on error, right?
try {
refresh();
} catch (refreshErr) {
if (callback) {
callback(refreshErr);
return;
} else {
throw refreshErr;
}
}
}
write.committed();
if (callback) {
callback(err, result);
} else if (err) {
throw err;
}
};
};
var bindEnvironmentForWrite = function (callback) {
return Meteor.bindEnvironment(callback, "Mongo write");
};
MongoConnection.prototype._insert = function (collection_name, document,
callback) {
var self = this;
var sendError = function (e) {
if (callback)
return callback(e);
throw e;
};
if (collection_name === "___meteor_failure_test_collection") {
var e = new Error("Failure test");
e._expectedByTest = true;
sendError(e);
return;
}
if (!(LocalCollection._isPlainObject(document) &&
!EJSON._isCustomType(document))) {
sendError(new Error(
"Only plain objects may be inserted into MongoDB"));
return;
}
var write = self._maybeBeginWrite();
var refresh = function () {
Meteor.refresh({collection: collection_name, id: document._id });
};
callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));
try {
var collection = self.rawCollection(collection_name);
collection.insertOne(
replaceTypes(document, replaceMeteorAtomWithMongo),
{
safe: true,
}
).then(({insertedId}) => {
callback(null, insertedId);
}).catch((e) => {
callback(e, null)
});
} catch (err) {
write.committed();
throw err;
}
};
// Cause queries that may be affected by the selector to poll in this write
// fence.
MongoConnection.prototype._refresh = function (collectionName, selector) {
var refreshKey = {collection: collectionName};
// If we know which documents we're removing, don't poll queries that are
// specific to other documents. (Note that multiple notifications here should
// not cause multiple polls, since all our listener is doing is enqueueing a
// poll.)
var specificIds = LocalCollection._idsMatchedBySelector(selector);
if (specificIds) {
_.each(specificIds, function (id) {
Meteor.refresh(_.extend({id: id}, refreshKey));
});
} else {
Meteor.refresh(refreshKey);
}
};
MongoConnection.prototype._remove = function (collection_name, selector,
callback) {
var self = this;
if (collection_name === "___meteor_failure_test_collection") {
var e = new Error("Failure test");
e._expectedByTest = true;
if (callback) {
return callback(e);
} else {
throw e;
}
}
var write = self._maybeBeginWrite();
var refresh = function () {
self._refresh(collection_name, selector);
};
callback = bindEnvironmentForWrite(writeCallback(write, refresh, callback));
try {
var collection = self.rawCollection(collection_name);
collection
.deleteMany(replaceTypes(selector, replaceMeteorAtomWithMongo), {
safe: true,
})
.then(({ deletedCount }) => {
callback(null, transformResult({ result : {modifiedCount : deletedCount} }).numberAffected);
}).catch((err) => {
callback(err);
});
} catch (err) {
write.committed();
throw err;
}
};
MongoConnection.prototype._dropCollection = function (collectionName, cb) {
var self = this;
var write = self._maybeBeginWrite();
var refresh = function () {
Meteor.refresh({collection: collectionName, id: null,
dropCollection: true});
};
cb = bindEnvironmentForWrite(writeCallback(write, refresh, cb));
try {
var collection = self.rawCollection(collectionName);
collection.drop(cb);
} catch (e) {
write.committed();
throw e;
}
};
// For testing only. Slightly better than `c.rawDatabase().dropDatabase()`
// because it lets the test's fence wait for it to be complete.
MongoConnection.prototype._dropDatabase = function (cb) {
var self = this;
var write = self._maybeBeginWrite();
var refresh = function () {
Meteor.refresh({ dropDatabase: true });
};
cb = bindEnvironmentForWrite(writeCallback(write, refresh, cb));
try {
self.db.dropDatabase(cb);
} catch (e) {
write.committed();
throw e;
}
};
MongoConnection.prototype._update = function (collection_name, selector, mod,
options, callback) {
var self = this;
if (! callback && options instanceof Function) {
callback = options;
options = null;
}
if (collection_name === "___meteor_failure_test_collection") {
var e = new Error("Failure test");
e._expectedByTest = true;
if (callback) {
return callback(e);
} else {
throw e;
}
}
// explicit safety check. null and undefined can crash the mongo
// driver. Although the node driver and minimongo do 'support'
// non-object modifier in that they don't crash, they are not
// meaningful operations and do not do anything. Defensively throw an
// error here.
if (!mod || typeof mod !== 'object')
throw new Error("Invalid modifier. Modifier must be an object.");
if (!(LocalCollection._isPlainObject(mod) &&
!EJSON._isCustomType(mod))) {
throw new Error(
"Only plain objects may be used as replacement" +
" documents in MongoDB");
}
if (!options) options = {};
var write = self._maybeBeginWrite();
var refresh = function () {
self._refresh(collection_name, selector);
};
callback = writeCallback(write, refresh, callback);
try {
var collection = self.rawCollection(collection_name);
var mongoOpts = {safe: true};
// Add support for filtered positional operator
if (options.arrayFilters !== undefined) mongoOpts.arrayFilters = options.arrayFilters;
// explictly enumerate options that minimongo supports
if (options.upsert) mongoOpts.upsert = true;
if (options.multi) mongoOpts.multi = true;
// Lets you get a more more full result from MongoDB. Use with caution:
// might not work with C.upsert (as opposed to C.update({upsert:true}) or
// with simulated upsert.
if (options.fullResult) mongoOpts.fullResult = true;
var mongoSelector = replaceTypes(selector, replaceMeteorAtomWithMongo);
var mongoMod = replaceTypes(mod, replaceMeteorAtomWithMongo);
var isModify = LocalCollection._isModificationMod(mongoMod);
if (options._forbidReplace && !isModify) {
var err = new Error("Invalid modifier. Replacements are forbidden.");
if (callback) {
return callback(err);
} else {
throw err;
}
}
// We've already run replaceTypes/replaceMeteorAtomWithMongo on
// selector and mod. We assume it doesn't matter, as far as
// the behavior of modifiers is concerned, whether `_modify`
// is run on EJSON or on mongo-converted EJSON.
// Run this code up front so that it fails fast if someone uses
// a Mongo update operator we don't support.
let knownId;
if (options.upsert) {
try {
let newDoc = LocalCollection._createUpsertDocument(selector, mod);
knownId = newDoc._id;
} catch (err) {
if (callback) {
return callback(err);
} else {
throw err;
}
}
}
if (options.upsert &&
! isModify &&
! knownId &&
options.insertedId &&
! (options.insertedId instanceof Mongo.ObjectID &&
options.generatedId)) {
// In case of an upsert with a replacement, where there is no _id defined
// in either the query or the replacement doc, mongo will generate an id itself.
// Therefore we need this special strategy if we want to control the id ourselves.
// We don't need to do this when:
// - This is not a replacement, so we can add an _id to $setOnInsert
// - The id is defined by query or mod we can just add it to the replacement doc
// - The user did not specify any id preference and the id is a Mongo ObjectId,
// then we can just let Mongo generate the id
simulateUpsertWithInsertedId(
collection, mongoSelector, mongoMod, options,
// This callback does not need to be bindEnvironment'ed because
// simulateUpsertWithInsertedId() wraps it and then passes it through
// bindEnvironmentForWrite.
function (error, result) {
// If we got here via a upsert() call, then options._returnObject will
// be set and we should return the whole object. Otherwise, we should
// just return the number of affected docs to match the mongo API.
if (result && ! options._returnObject) {
callback(error, result.numberAffected);
} else {
callback(error, result);
}
}
);
} else {
if (options.upsert && !knownId && options.insertedId && isModify) {
if (!mongoMod.hasOwnProperty('$setOnInsert')) {
mongoMod.$setOnInsert = {};
}
knownId = options.insertedId;
Object.assign(mongoMod.$setOnInsert, replaceTypes({_id: options.insertedId}, replaceMeteorAtomWithMongo));
}
const strings = Object.keys(mongoMod).filter((key) => !key.startsWith("$"));
let updateMethod = strings.length > 0 ? 'replaceOne' : 'updateMany';
updateMethod =
updateMethod === 'updateMany' && !mongoOpts.multi
? 'updateOne'
: updateMethod;
collection[updateMethod].bind(collection)(
mongoSelector, mongoMod, mongoOpts,
// mongo driver now returns undefined for err in the callback
bindEnvironmentForWrite(function (err = null, result) {
if (! err) {
var meteorResult = transformResult({result});
if (meteorResult && options._returnObject) {
// If this was an upsert() call, and we ended up
// inserting a new doc and we know its id, then
// return that id as well.
if (options.upsert && meteorResult.insertedId) {
if (knownId) {
meteorResult.insertedId = knownId;
} else if (meteorResult.insertedId instanceof MongoDB.ObjectID) {
meteorResult.insertedId = new Mongo.ObjectID(meteorResult.insertedId.toHexString());
}
}
callback(err, meteorResult);
} else {
callback(err, meteorResult.numberAffected);
}
} else {
callback(err);
}
}));
}
} catch (e) {
write.committed();
throw e;
}
};
var transformResult = function (driverResult) {
var meteorResult = { numberAffected: 0 };
if (driverResult) {
var mongoResult = driverResult.result;
// On updates with upsert:true, the inserted values come as a list of
// upserted values -- even with options.multi, when the upsert does insert,
// it only inserts one element.
if (mongoResult.upsertedCount) {
meteorResult.numberAffected = mongoResult.upsertedCount;
if (mongoResult.upsertedId) {
meteorResult.insertedId = mongoResult.upsertedId;
}
} else {
// n was used before Mongo 5.0, in Mongo 5.0 we are not receiving this n
// field and so we are using modifiedCount instead
meteorResult.numberAffected = mongoResult.n || mongoResult.matchedCount || mongoResult.modifiedCount;
}
}
return meteorResult;
};
var NUM_OPTIMISTIC_TRIES = 3;
// exposed for testing
MongoConnection._isCannotChangeIdError = function (err) {
// Mongo 3.2.* returns error as next Object:
// {name: String, code: Number, errmsg: String}
// Older Mongo returns:
// {name: String, code: Number, err: String}
var error = err.errmsg || err.err;
// We don't use the error code here
// because the error code we observed it producing (16837) appears to be
// a far more generic error code based on examining the source.
if (error.indexOf('The _id field cannot be changed') === 0
|| error.indexOf("the (immutable) field '_id' was found to have been altered to _id") !== -1) {
return true;
}
return false;
};
var simulateUpsertWithInsertedId = function (collection, selector, mod,
options, callback) {
// STRATEGY: First try doing an upsert with a generated ID.
// If this throws an error about changing the ID on an existing document
// then without affecting the database, we know we should probably try
// an update without the generated ID. If it affected 0 documents,
// then without affecting the database, we the document that first
// gave the error is probably removed and we need to try an insert again
// We go back to step one and repeat.
// Like all "optimistic write" schemes, we rely on the fact that it's
// unlikely our writes will continue to be interfered with under normal
// circumstances (though sufficiently heavy contention with writers
// disagreeing on the existence of an object will cause writes to fail
// in theory).
var insertedId = options.insertedId; // must exist
var mongoOptsForUpdate = {
safe: true,
multi: options.multi
};
var mongoOptsForInsert = {
safe: true,
upsert: true
};
var replacementWithId = Object.assign(
replaceTypes({_id: insertedId}, replaceMeteorAtomWithMongo),
mod);
var tries = NUM_OPTIMISTIC_TRIES;
var doUpdate = function () {
tries--;
if (! tries) {
callback(new Error("Upsert failed after " + NUM_OPTIMISTIC_TRIES + " tries."));
} else {
let method = collection.updateMany;
if(!Object.keys(mod).some(key => key.startsWith("$"))){
method = collection.replaceOne.bind(collection);
}
method(
selector,
mod,
mongoOptsForUpdate,
bindEnvironmentForWrite(function(err, result) {
if (err) {
callback(err);
} else if (result && (result.modifiedCount || result.upsertedCount)) {
callback(null, {
numberAffected: result.modifiedCount || result.upsertedCount,
insertedId: result.upsertedId || undefined,
});
} else {
doConditionalInsert();
}
})
);
}
};
var doConditionalInsert = function() {
collection.replaceOne(
selector,
replacementWithId,
mongoOptsForInsert,
bindEnvironmentForWrite(function(err, result) {
if (err) {
// figure out if this is a
// "cannot change _id of document" error, and
// if so, try doUpdate() again, up to 3 times.
if (MongoConnection._isCannotChangeIdError(err)) {
doUpdate();
} else {
callback(err);
}
} else {
callback(null, {
numberAffected: result.upsertedCount,
insertedId: result.upsertedId,
});
}
})
);
};
doUpdate();
};
_.each(["insert", "update", "remove", "dropCollection", "dropDatabase"], function (method) {
MongoConnection.prototype[method] = function (/* arguments */) {
var self = this;
return Meteor.wrapAsync(self["_" + method]).apply(self, arguments);
};
});
// XXX MongoConnection.upsert() does not return the id of the inserted document
// unless you set it explicitly in the selector or modifier (as a replacement
// doc).
MongoConnection.prototype.upsert = function (collectionName, selector, mod,
options, callback) {
var self = this;
if (typeof options === "function" && ! callback) {
callback = options;
options = {};
}
return self.update(collectionName, selector, mod,
_.extend({}, options, {
upsert: true,
_returnObject: true
}), callback);
};
MongoConnection.prototype.find = function (collectionName, selector, options) {
var self = this;
if (arguments.length === 1)
selector = {};
return new Cursor(
self, new CursorDescription(collectionName, selector, options));
};
MongoConnection.prototype.findOneAsync = async function (collection_name, selector,
options) {
var self = this;
if (arguments.length === 1)
selector = {};
options = options || {};
options.limit = 1;
return (await self.find(collection_name, selector, options).fetchAsync())[0];
};
MongoConnection.prototype.findOne = function (collection_name, selector,
options) {
var self = this;
return Future.fromPromise(self.findOneAsync(collection_name, selector, options)).wait();
};
MongoConnection.prototype.createIndexAsync = function (collectionName, index,
options) {
var self = this;
// We expect this function to be called at startup, not from within a method,
// so we don't interact with the write fence.
var collection = self.rawCollection(collectionName);
return collection.createIndex(index, options);
};
// We'll actually design an index API later. For now, we just pass through to
// Mongo's, but make it synchronous.
MongoConnection.prototype.createIndex = function (collectionName, index,
options) {
var self = this;
return Future.fromPromise(self.createIndexAsync(collectionName, index, options));
};
MongoConnection.prototype.countDocuments = function (collectionName, ...args) {
args = args.map(arg => replaceTypes(arg, replaceMeteorAtomWithMongo));
const collection = this.rawCollection(collectionName);
return collection.countDocuments(...args);
};
MongoConnection.prototype.estimatedDocumentCount = function (collectionName, ...args) {
args = args.map(arg => replaceTypes(arg, replaceMeteorAtomWithMongo));
const collection = this.rawCollection(collectionName);
return collection.estimatedDocumentCount(...args);
};
MongoConnection.prototype._ensureIndex = MongoConnection.prototype.createIndex;
MongoConnection.prototype._dropIndex = function (collectionName, index) {
var self = this;
// This function is only used by test code, not within a method, so we don't
// interact with the write fence.
var collection = self.rawCollection(collectionName);
var future = new Future;
var indexName = collection.dropIndex(index, future.resolver());
future.wait();
};
// CURSORS
// There are several classes which relate to cursors:
//
// CursorDescription represents the arguments used to construct a cursor:
// collectionName, selector, and (find) options. Because it is used as a key
// for cursor de-dup, everything in it should either be JSON-stringifiable or
// not affect observeChanges output (eg, options.transform functions are not
// stringifiable but do not affect observeChanges).
//
// SynchronousCursor is a wrapper around a MongoDB cursor
// which includes fully-synchronous versions of forEach, etc.
//
// Cursor is the cursor object returned from find(), which implements the
// documented Mongo.Collection cursor API. It wraps a CursorDescription and a
// SynchronousCursor (lazily: it doesn't contact Mongo until you call a method
// like fetch or forEach on it).
//
// ObserveHandle is the "observe handle" returned from observeChanges. It has a
// reference to an ObserveMultiplexer.
//
// ObserveMultiplexer allows multiple identical ObserveHandles to be driven by a
// single observe driver.
//
// There are two "observe drivers" which drive ObserveMultiplexers:
// - PollingObserveDriver caches the results of a query and reruns it when
// necessary.
// - OplogObserveDriver follows the Mongo operation log to directly observe
// database changes.
// Both implementations follow the same simple interface: when you create them,
// they start sending observeChanges callbacks (and a ready() invocation) to
// their ObserveMultiplexer, and you stop them by calling their stop() method.
CursorDescription = function (collectionName, selector, options) {
var self = this;
self.collectionName = collectionName;
self.selector = Mongo.Collection._rewriteSelector(selector);
self.options = options || {};
};
Cursor = function (mongo, cursorDescription) {
var self = this;
self._mongo = mongo;
self._cursorDescription = cursorDescription;
self._synchronousCursor = null;
};
function setupSynchronousCursor(cursor, method) {
// You can only observe a tailable cursor.
if (cursor._cursorDescription.options.tailable)
throw new Error('Cannot call ' + method + ' on a tailable cursor');
if (!cursor._synchronousCursor) {
cursor._synchronousCursor = cursor._mongo._createSynchronousCursor(
cursor._cursorDescription,
{
// Make sure that the "cursor" argument to forEach/map callbacks is the
// Cursor, not the SynchronousCursor.
selfForIteration: cursor,
useTransform: true,
}
);
}
return cursor._synchronousCursor;
}
Cursor.prototype.count = function () {
const collection = this._mongo.rawCollection(this._cursorDescription.collectionName);
return Promise.await(collection.countDocuments(
replaceTypes(this._cursorDescription.selector, replaceMeteorAtomWithMongo),
replaceTypes(this._cursorDescription.options, replaceMeteorAtomWithMongo),
));
};
[...ASYNC_CURSOR_METHODS, Symbol.iterator, Symbol.asyncIterator].forEach(methodName => {
// count is handled specially since we don't want to create a cursor.
// it is still included in ASYNC_CURSOR_METHODS because we still want an async version of it to exist.
if (methodName !== 'count') {
Cursor.prototype[methodName] = function (...args) {
const cursor = setupSynchronousCursor(this, methodName);
return cursor[methodName](...args);
};
}
// These methods are handled separately.
if (methodName === Symbol.iterator || methodName === Symbol.asyncIterator) {
return;
}
const methodNameAsync = getAsyncMethodName(methodName);
Cursor.prototype[methodNameAsync] = function (...args) {
try {
this[methodName].isCalledFromAsync = true;
return Promise.resolve(this[methodName](...args));
} catch (error) {
return Promise.reject(error);
}
};
});
Cursor.prototype.getTransform = function () {
return this._cursorDescription.options.transform;
};
// When you call Meteor.publish() with a function that returns a Cursor, we need
// to transmute it into the equivalent subscription. This is the function that
// does that.
Cursor.prototype._publishCursor = function (sub) {
var self = this;
var collection = self._cursorDescription.collectionName;
return Mongo.Collection._publishCursor(self, sub, collection);