-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
connection.js
1559 lines (1377 loc) · 50.2 KB
/
connection.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
'use strict';
/*!
* Module dependencies.
*/
const ChangeStream = require('./cursor/changeStream');
const EventEmitter = require('events').EventEmitter;
const Schema = require('./schema');
const STATES = require('./connectionState');
const MongooseError = require('./error/index');
const ServerSelectionError = require('./error/serverSelection');
const SyncIndexesError = require('./error/syncIndexes');
const applyPlugins = require('./helpers/schema/applyPlugins');
const clone = require('./helpers/clone');
const driver = require('./driver');
const get = require('./helpers/get');
const immediate = require('./helpers/immediate');
const utils = require('./utils');
const CreateCollectionsError = require('./error/createCollectionsError');
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
const sessionNewDocuments = require('./helpers/symbols').sessionNewDocuments;
/**
* A list of authentication mechanisms that don't require a password for authentication.
* This is used by the authMechanismDoesNotRequirePassword method.
*
* @api private
*/
const noPasswordAuthMechanisms = [
'MONGODB-X509'
];
/**
* Connection constructor
*
* For practical reasons, a Connection equals a Db.
*
* @param {Mongoose} base a mongoose instance
* @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
* @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
* @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
* @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connection's models.
* @event `disconnecting`: Emitted when `connection.close()` was executed.
* @event `disconnected`: Emitted after getting disconnected from the db.
* @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connection's models.
* @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection.
* @event `error`: Emitted when an error occurs on this connection.
* @event `operation-start`: Emitted when a call to the MongoDB Node.js driver, like a `find()` or `insertOne()`, happens on any collection tied to this connection.
* @event `operation-end`: Emitted when a call to the MongoDB Node.js driver, like a `find()` or `insertOne()`, either succeeds or errors.
* @api public
*/
function Connection(base) {
this.base = base;
this.collections = {};
this.models = {};
this.config = {};
this.replica = false;
this.options = null;
this.otherDbs = []; // FIXME: To be replaced with relatedDbs
this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection
this.states = STATES;
this._readyState = STATES.disconnected;
this._closeCalled = false;
this._hasOpened = false;
this.plugins = [];
if (typeof base === 'undefined' || !base.connections.length) {
this.id = 0;
} else {
this.id = base.nextConnectionId;
}
this._queue = [];
}
/*!
* Inherit from EventEmitter
*/
Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype);
/**
* Connection ready state
*
* - 0 = disconnected
* - 1 = connected
* - 2 = connecting
* - 3 = disconnecting
*
* Each state change emits its associated event name.
*
* #### Example:
*
* conn.on('connected', callback);
* conn.on('disconnected', callback);
*
* @property readyState
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'readyState', {
get: function() {
return this._readyState;
},
set: function(val) {
if (!(val in STATES)) {
throw new Error('Invalid connection state: ' + val);
}
if (this._readyState !== val) {
this._readyState = val;
// [legacy] loop over the otherDbs on this connection and change their state
for (const db of this.otherDbs) {
db.readyState = val;
}
if (STATES.connected === val) {
this._hasOpened = true;
}
this.emit(STATES[val]);
}
}
});
/**
* Gets the value of the option `key`. Equivalent to `conn.options[key]`
*
* #### Example:
*
* conn.get('test'); // returns the 'test' value
*
* @param {String} key
* @method get
* @api public
*/
Connection.prototype.get = function(key) {
if (this.config.hasOwnProperty(key)) {
return this.config[key];
}
return get(this.options, key);
};
/**
* Sets the value of the option `key`. Equivalent to `conn.options[key] = val`
*
* Supported options include:
*
* - `maxTimeMS`: Set [`maxTimeMS`](https://mongoosejs.com/docs/api/query.html#Query.prototype.maxTimeMS()) for all queries on this connection.
* - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`.
*
* #### Example:
*
* conn.set('test', 'foo');
* conn.get('test'); // 'foo'
* conn.options.test; // 'foo'
*
* @param {String} key
* @param {Any} val
* @method set
* @api public
*/
Connection.prototype.set = function(key, val) {
if (this.config.hasOwnProperty(key)) {
this.config[key] = val;
return val;
}
this.options = this.options || {};
this.options[key] = val;
return val;
};
/**
* A hash of the collections associated with this connection
*
* @property collections
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.collections;
/**
* The name of the database this connection points to.
*
* #### Example:
*
* mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb"
*
* @property name
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.name;
/**
* A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
* a map from model names to models. Contains all models that have been
* added to this connection using [`Connection#model()`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.model()).
*
* #### Example:
*
* const conn = mongoose.createConnection();
* const Test = conn.model('Test', mongoose.Schema({ name: String }));
*
* Object.keys(conn.models).length; // 1
* conn.models.Test === Test; // true
*
* @property models
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.models;
/**
* A number identifier for this connection. Used for debugging when
* you have [multiple connections](https://mongoosejs.com/docs/connections.html#multiple_connections).
*
* #### Example:
*
* // The default connection has `id = 0`
* mongoose.connection.id; // 0
*
* // If you create a new connection, Mongoose increments id
* const conn = mongoose.createConnection();
* conn.id; // 1
*
* @property id
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.id;
/**
* The plugins that will be applied to all models created on this connection.
*
* #### Example:
*
* const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
* db.plugin(() => console.log('Applied'));
* db.plugins.length; // 1
*
* db.model('Test', new Schema({})); // Prints "Applied"
*
* @property plugins
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'plugins', {
configurable: false,
enumerable: true,
writable: true
});
/**
* The host name portion of the URI. If multiple hosts, such as a replica set,
* this will contain the first host name in the URI
*
* #### Example:
*
* mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').host; // "127.0.0.1"
*
* @property host
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'host', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The port portion of the URI. If multiple hosts, such as a replica set,
* this will contain the port from the first host name in the URI.
*
* #### Example:
*
* mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').port; // 27017
*
* @property port
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'port', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The username specified in the URI
*
* #### Example:
*
* mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').user; // "val"
*
* @property user
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'user', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The password specified in the URI
*
* #### Example:
*
* mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').pass; // "psw"
*
* @property pass
* @memberOf Connection
* @instance
* @api public
*/
Object.defineProperty(Connection.prototype, 'pass', {
configurable: true,
enumerable: true,
writable: true
});
/**
* The mongodb.Db instance, set when the connection is opened
*
* @property db
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.db;
/**
* The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property
* when the connection is opened.
*
* @property client
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.client;
/**
* A hash of the global options that are associated with this connection
*
* @property config
* @memberOf Connection
* @instance
* @api public
*/
Connection.prototype.config;
/**
* Helper for `createCollection()`. Will explicitly create the given collection
* with specified options. Used to create [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections/)
* and [views](https://www.mongodb.com/docs/manual/core/views/) from mongoose.
*
* Options are passed down without modification to the [MongoDB driver's `createCollection()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Db.html#createCollection)
*
* @method createCollection
* @param {string} collection The collection to create
* @param {Object} [options] see [MongoDB driver docs](https://mongodb.github.io/node-mongodb-native/4.9/classes/Db.html#createCollection)
* @return {Promise}
* @api public
*/
Connection.prototype.createCollection = async function createCollection(collection, options) {
if (typeof options === 'function' || (arguments.length >= 3 && typeof arguments[2] === 'function')) {
throw new MongooseError('Connection.prototype.createCollection() no longer accepts a callback');
}
await this._waitForConnect();
return this.db.createCollection(collection, options);
};
/**
* Calls `createCollection()` on a models in a series.
*
* @method createCollections
* @param {Boolean} continueOnError When true, will continue to create collections and create a new error class for the collections that errored.
* @returns {Promise}
* @api public
*/
Connection.prototype.createCollections = async function createCollections(options = {}) {
const result = {};
const errorsMap = { };
const { continueOnError } = options;
delete options.continueOnError;
for (const model of Object.values(this.models)) {
try {
result[model.modelName] = await model.createCollection({});
} catch (err) {
if (!continueOnError) {
errorsMap[model.modelName] = err;
break;
} else {
result[model.modelName] = err;
}
}
}
if (!continueOnError && Object.keys(errorsMap).length) {
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
const createCollectionsError = new CreateCollectionsError(message, errorsMap);
throw createCollectionsError;
}
return result;
};
/**
* A convenience wrapper for `connection.client.withSession()`.
*
* #### Example:
*
* await conn.withSession(async session => {
* const doc = await TestModel.findOne().session(session);
* });
*
* @method withSession
* @param {Function} executor called with 1 argument: a `ClientSession` instance
* @return {Promise} resolves to the return value of the executor function
* @api public
*/
Connection.prototype.withSession = async function withSession(executor) {
if (arguments.length === 0) {
throw new Error('Please provide an executor function');
}
return await this.client.withSession(executor);
};
/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
* and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
*
* #### Example:
*
* const session = await conn.startSession();
* let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
* await doc.remove();
* // `doc` will always be null, even if reading from a replica set
* // secondary. Without causal consistency, it is possible to
* // get a doc back from the below query if the query reads from a
* // secondary that is experiencing replication lag.
* doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
*
*
* @method startSession
* @param {Object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html#startSession)
* @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
* @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
* @api public
*/
Connection.prototype.startSession = async function startSession(options) {
if (arguments.length >= 2 && typeof arguments[1] === 'function') {
throw new MongooseError('Connection.prototype.startSession() no longer accepts a callback');
}
await this._waitForConnect();
const session = this.client.startSession(options);
return session;
};
/**
* _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
* in a transaction. Mongoose will commit the transaction if the
* async function executes successfully and attempt to retry if
* there was a retriable error.
*
* Calls the MongoDB driver's [`session.withTransaction()`](https://mongodb.github.io/node-mongodb-native/4.9/classes/ClientSession.html#withTransaction),
* but also handles resetting Mongoose document state as shown below.
*
* #### Example:
*
* const doc = new Person({ name: 'Will Riker' });
* await db.transaction(async function setRank(session) {
* doc.rank = 'Captain';
* await doc.save({ session });
* doc.isNew; // false
*
* // Throw an error to abort the transaction
* throw new Error('Oops!');
* },{ readPreference: 'primary' }).catch(() => {});
*
* // true, `transaction()` reset the document's state because the
* // transaction was aborted.
* doc.isNew;
*
* @method transaction
* @param {Function} fn Function to execute in a transaction
* @param {mongodb.TransactionOptions} [options] Optional settings for the transaction
* @return {Promise<Any>} promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result.
* @api public
*/
Connection.prototype.transaction = function transaction(fn, options) {
return this.startSession().then(session => {
session[sessionNewDocuments] = new Map();
return session.withTransaction(() => _wrapUserTransaction(fn, session, this.base), options).
then(res => {
delete session[sessionNewDocuments];
return res;
}).
catch(err => {
delete session[sessionNewDocuments];
throw err;
}).
finally(() => {
session.endSession().catch(() => {});
});
});
};
/*!
* Reset document state in between transaction retries re: gh-13698
*/
async function _wrapUserTransaction(fn, session, mongoose) {
try {
const res = mongoose.transactionAsyncLocalStorage == null
? await fn(session)
: await new Promise(resolve => {
mongoose.transactionAsyncLocalStorage.run(
{ session },
() => resolve(fn(session))
);
});
return res;
} catch (err) {
_resetSessionDocuments(session);
throw err;
}
}
/*!
* If transaction was aborted, we need to reset newly inserted documents' `isNew`.
*/
function _resetSessionDocuments(session) {
for (const doc of session[sessionNewDocuments].keys()) {
const state = session[sessionNewDocuments].get(doc);
if (state.hasOwnProperty('isNew')) {
doc.$isNew = state.isNew;
}
if (state.hasOwnProperty('versionKey')) {
doc.set(doc.schema.options.versionKey, state.versionKey);
}
if (state.modifiedPaths.length > 0 && doc.$__.activePaths.states.modify == null) {
doc.$__.activePaths.states.modify = {};
}
for (const path of state.modifiedPaths) {
const currentState = doc.$__.activePaths.paths[path];
if (currentState != null) {
delete doc.$__.activePaths[currentState][path];
}
doc.$__.activePaths.paths[path] = 'modify';
doc.$__.activePaths.states.modify[path] = true;
}
for (const path of state.atomics.keys()) {
const val = doc.$__getValue(path);
if (val == null) {
continue;
}
val[arrayAtomicsSymbol] = state.atomics.get(path);
}
}
}
/**
* Helper for `dropCollection()`. Will delete the given collection, including
* all documents and indexes.
*
* @method dropCollection
* @param {string} collection The collection to delete
* @return {Promise}
* @api public
*/
Connection.prototype.dropCollection = async function dropCollection(collection) {
if (arguments.length >= 2 && typeof arguments[1] === 'function') {
throw new MongooseError('Connection.prototype.dropCollection() no longer accepts a callback');
}
await this._waitForConnect();
return this.db.dropCollection(collection);
};
/**
* Waits for connection to be established, so the connection has a `client`
*
* @return Promise
* @api private
*/
Connection.prototype._waitForConnect = async function _waitForConnect() {
if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
await new Promise(resolve => {
this._queue.push({ fn: resolve });
});
}
};
/**
* Helper for MongoDB Node driver's `listCollections()`.
* Returns an array of collection objects.
*
* @method listCollections
* @return {Promise<Collection[]>}
* @api public
*/
Connection.prototype.listCollections = async function listCollections() {
await this._waitForConnect();
const cursor = this.db.listCollections();
return await cursor.toArray();
};
/**
* Helper for MongoDB Node driver's `listDatabases()`.
* Returns an object with a `databases` property that contains an
* array of database objects.
*
* #### Example:
* const { databases } = await mongoose.connection.listDatabases();
* databases; // [{ name: 'mongoose_test', sizeOnDisk: 0, empty: false }]
*
* @method listCollections
* @return {Promise<{ databases: Array<{ name: string }> }>}
* @api public
*/
Connection.prototype.listDatabases = async function listDatabases() {
// Implemented in `lib/drivers/node-mongodb-native/connection.js`
throw new MongooseError('listDatabases() not implemented by driver');
};
/**
* Helper for `dropDatabase()`. Deletes the given database, including all
* collections, documents, and indexes.
*
* #### Example:
*
* const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
* // Deletes the entire 'mydb' database
* await conn.dropDatabase();
*
* @method dropDatabase
* @return {Promise}
* @api public
*/
Connection.prototype.dropDatabase = async function dropDatabase() {
if (arguments.length >= 1 && typeof arguments[0] === 'function') {
throw new MongooseError('Connection.prototype.dropDatabase() no longer accepts a callback');
}
await this._waitForConnect();
// If `dropDatabase()` is called, this model's collection will not be
// init-ed. It is sufficiently common to call `dropDatabase()` after
// `mongoose.connect()` but before creating models that we want to
// support this. See gh-6796
for (const model of Object.values(this.models)) {
delete model.$init;
}
return this.db.dropDatabase();
};
/*!
* ignore
*/
Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() {
if (this.config.bufferCommands != null) {
return this.config.bufferCommands;
}
if (this.base.get('bufferCommands') != null) {
return this.base.get('bufferCommands');
}
return true;
};
/**
* error
*
* Graceful error handling, passes error to callback
* if available, else emits error on the connection.
*
* @param {Error} err
* @param {Function} callback optional
* @emits "error" Emits the `error` event with the given `err`, unless a callback is specified
* @returns {Promise|null} Returns a rejected Promise if no `callback` is given.
* @api private
*/
Connection.prototype.error = function(err, callback) {
if (callback) {
callback(err);
return null;
}
if (this.listeners('error').length > 0) {
this.emit('error', err);
}
return Promise.reject(err);
};
/**
* Called when the connection is opened
*
* @api private
*/
Connection.prototype.onOpen = function() {
this.readyState = STATES.connected;
for (const d of this._queue) {
d.fn.apply(d.ctx, d.args);
}
this._queue = [];
// avoid having the collection subscribe to our event emitter
// to prevent 0.3 warning
for (const i in this.collections) {
if (utils.object.hasOwnProperty(this.collections, i)) {
this.collections[i].onOpen();
}
}
this.emit('open');
};
/**
* Opens the connection with a URI using `MongoClient.connect()`.
*
* @param {String} uri The URI to connect with.
* @param {Object} [options] Passed on to [`MongoClient.connect`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html#connect-1)
* @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](https://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
* @param {Number} [options.bufferTimeoutMS=10000] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered.
* @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
* @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
* @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
* @param {Number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
* @param {Number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
* @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
* @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
* @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
* @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/MongoClientOptions.html#promiseLibrary).
* @param {Number} [options.socketTimeoutMS=0] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. `socketTimeoutMS` defaults to 0, which means Node.js will not time out the socket due to inactivity. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
* @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
* @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
* @returns {Promise<Connection>}
* @api public
*/
Connection.prototype.openUri = async function openUri(uri, options) {
if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
if (this._connectionString === uri) {
return this;
}
}
this._closeCalled = false;
// Internal option to skip `await this.$initialConnection` in
// this function for `createConnection()`. Because otherwise
// `createConnection()` would have an uncatchable error.
let _fireAndForget = false;
if (options && '_fireAndForget' in options) {
_fireAndForget = options._fireAndForget;
delete options._fireAndForget;
}
try {
_validateArgs.apply(arguments);
} catch (err) {
if (_fireAndForget) {
throw err;
}
this.$initialConnection = Promise.reject(err);
throw err;
}
this.$initialConnection = this.createClient(uri, options).
then(() => this).
catch(err => {
this.readyState = STATES.disconnected;
if (this.listeners('error').length > 0) {
immediate(() => this.emit('error', err));
}
throw err;
});
for (const model of Object.values(this.models)) {
// Errors handled internally, so safe to ignore error
model.init().catch(function $modelInitNoop() {});
}
// `createConnection()` calls this `openUri()` function without
// awaiting on the result, so we set this option to rely on
// `asPromise()` to handle any errors.
if (_fireAndForget) {
return this;
}
try {
await this.$initialConnection;
} catch (err) {
throw _handleConnectionErrors(err);
}
return this;
};
/*!
* Treat `on('error')` handlers as handling the initialConnection promise
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
*/
Connection.prototype.on = function on(event, callback) {
if (event === 'error' && this.$initialConnection) {
this.$initialConnection.catch(() => {});
}
return EventEmitter.prototype.on.call(this, event, callback);
};
/*!
* Treat `once('error')` handlers as handling the initialConnection promise
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
*/
Connection.prototype.once = function on(event, callback) {
if (event === 'error' && this.$initialConnection) {
this.$initialConnection.catch(() => {});
}
return EventEmitter.prototype.once.call(this, event, callback);
};
/*!
* ignore
*/
function _validateArgs(uri, options, callback) {
if (typeof options === 'function' && callback == null) {
throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
} else if (typeof callback === 'function') {
throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
}
}
/*!
* ignore
*/
function _handleConnectionErrors(err) {
if (err?.name === 'MongoServerSelectionError') {
const originalError = err;
err = new ServerSelectionError();
err.assimilateError(originalError);
}
return err;
}
/**
* Destroy the connection. Similar to [`.close`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.close()),
* but also removes the connection from Mongoose's `connections` list and prevents the
* connection from ever being re-opened.
*
* @param {Boolean} [force]
* @returns {Promise}
*/
Connection.prototype.destroy = async function destroy(force) {
if (typeof force === 'function' || (arguments.length === 2 && typeof arguments[1] === 'function')) {
throw new MongooseError('Connection.prototype.destroy() no longer accepts a callback');
}
if (force != null && typeof force === 'object') {
this.$wasForceClosed = !!force.force;
} else {
this.$wasForceClosed = !!force;
}
return this._close(force, true);
};
/**
* Closes the connection
*
* @param {Boolean} [force] optional
* @return {Promise}
* @api public
*/
Connection.prototype.close = async function close(force) {
if (typeof force === 'function' || (arguments.length === 2 && typeof arguments[1] === 'function')) {
throw new MongooseError('Connection.prototype.close() no longer accepts a callback');
}
if (force != null && typeof force === 'object') {
this.$wasForceClosed = !!force.force;
} else {
this.$wasForceClosed = !!force;
}
for (const model of Object.values(this.models)) {
// If manually disconnecting, make sure to clear each model's `$init`
// promise, so Mongoose knows to re-run `init()` in case the
// connection is re-opened. See gh-12047.
delete model.$init;
}
return this._close(force, false);
};
/**
* Handles closing the connection
*
* @param {Boolean} force
* @param {Boolean} destroy
* @returns {Connection} this
* @api private
*/
Connection.prototype._close = async function _close(force, destroy) {
const _this = this;
const closeCalled = this._closeCalled;
this._closeCalled = true;
this._destroyCalled = destroy;
if (this.client != null) {
this.client._closeCalled = true;
this.client._destroyCalled = destroy;
}
const conn = this;
switch (this.readyState) {
case STATES.disconnected:
if (destroy && this.base.connections.indexOf(conn) !== -1) {
this.base.connections.splice(this.base.connections.indexOf(conn), 1);
}
if (!closeCalled) {
await this.doClose(force);
this.onClose(force);
}
break;
case STATES.connected:
this.readyState = STATES.disconnecting;
await this.doClose(force);
if (destroy && _this.base.connections.indexOf(conn) !== -1) {
this.base.connections.splice(this.base.connections.indexOf(conn), 1);
}
this.onClose(force);
break;
case STATES.connecting:
return new Promise((resolve, reject) => {
const _rerunClose = () => {
this.removeListener('open', _rerunClose);
this.removeListener('error', _rerunClose);
if (destroy) {