@datanimbus/mongoose 9.13.1 → 9.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -70
- package/eslint.config.mjs +202 -0
- package/index.js +2 -1
- package/lib/aggregate.js +276 -174
- package/lib/cast/bigint.js +46 -0
- package/lib/cast/boolean.js +3 -3
- package/lib/cast/decimal128.js +4 -1
- package/lib/cast/double.js +56 -0
- package/lib/cast/int32.js +42 -0
- package/lib/cast/number.js +6 -6
- package/lib/cast/objectid.js +3 -3
- package/lib/cast/string.js +3 -3
- package/lib/cast/uuid.js +35 -0
- package/lib/cast.js +100 -92
- package/lib/collection.js +31 -22
- package/lib/connection.js +792 -507
- package/lib/constants.js +73 -0
- package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
- package/lib/cursor/changeStream.js +218 -0
- package/lib/cursor/queryCursor.js +676 -0
- package/lib/defaults/schemaDefaultsCache.js +62 -0
- package/lib/document.js +2419 -1306
- package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
- package/lib/drivers/node-mongodb-native/collection.js +101 -135
- package/lib/drivers/node-mongodb-native/connection.js +386 -28
- package/lib/drivers/node-mongodb-native/index.js +3 -5
- package/lib/error/browserMissingSchema.js +5 -4
- package/lib/error/bulkSaveIncompleteError.js +44 -0
- package/lib/error/cast.js +30 -21
- package/lib/error/createCollectionsError.js +26 -0
- package/lib/error/divergentArray.js +11 -9
- package/lib/error/eachAsyncMultiError.js +2 -2
- package/lib/error/index.js +38 -29
- package/lib/error/invalidSchemaOption.js +32 -0
- package/lib/error/messages.js +4 -3
- package/lib/error/missingSchema.js +8 -6
- package/lib/error/notFound.js +7 -5
- package/lib/error/objectExpected.js +9 -8
- package/lib/error/objectParameter.js +12 -11
- package/lib/error/overwriteModel.js +7 -6
- package/lib/error/parallelSave.js +11 -8
- package/lib/error/parallelValidate.js +9 -7
- package/lib/error/serverSelection.js +1 -0
- package/lib/error/setOptionError.js +11 -9
- package/lib/error/strict.js +12 -10
- package/lib/error/strictPopulate.js +11 -9
- package/lib/error/syncIndexes.js +2 -2
- package/lib/error/validation.js +11 -17
- package/lib/error/validator.js +9 -8
- package/lib/error/version.js +12 -10
- package/lib/filters/operators.js +8 -0
- package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
- package/lib/helpers/buildMiddlewareFilter.js +42 -0
- package/lib/helpers/clone.js +121 -35
- package/lib/helpers/common.js +7 -7
- package/lib/helpers/cursor/eachAsync.js +14 -11
- package/lib/helpers/cursor/waitForInitialization.js +17 -0
- package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
- package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
- package/lib/helpers/discriminator/getConstructor.js +9 -6
- package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
- package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
- package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
- package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
- package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
- package/lib/helpers/document/applyDefaults.js +82 -14
- package/lib/helpers/document/applyTimestamps.js +106 -0
- package/lib/helpers/document/applyVirtuals.js +147 -0
- package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
- package/lib/helpers/document/compile.js +20 -15
- package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
- package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
- package/lib/helpers/document/handleSpreadDoc.js +2 -1
- package/lib/helpers/document/isInPathsToSave.js +24 -0
- package/lib/helpers/document/toObjectRecursive.js +49 -0
- package/lib/helpers/get.js +1 -1
- package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
- package/lib/helpers/getInheritedProperty.js +28 -0
- package/lib/helpers/getOwnProperty.js +19 -0
- package/lib/helpers/indexes/applySchemaCollation.js +1 -1
- package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
- package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
- package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
- package/lib/helpers/indexes/isIndexEqual.js +13 -12
- package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
- package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
- package/lib/helpers/isBsonType.js +3 -6
- package/lib/helpers/isMongooseDocument.js +24 -0
- package/lib/helpers/isMongooseObject.js +6 -4
- package/lib/helpers/isObject.js +2 -2
- package/lib/helpers/isPOJO.js +12 -0
- package/lib/helpers/isSimpleValidator.js +2 -2
- package/lib/helpers/minimize.js +41 -0
- package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
- package/lib/helpers/model/applyHooks.js +72 -54
- package/lib/helpers/model/applyMethods.js +3 -3
- package/lib/helpers/model/applyStaticHooks.js +20 -50
- package/lib/helpers/model/castBulkWrite.js +278 -172
- package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
- package/lib/helpers/model/discriminator.js +77 -21
- package/lib/helpers/omitUndefined.js +20 -0
- package/lib/helpers/parallelLimit.js +61 -34
- package/lib/helpers/path/setDottedPath.js +1 -1
- package/lib/helpers/pathTrie.js +167 -0
- package/lib/helpers/pluralize.js +5 -4
- package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
- package/lib/helpers/populate/assignVals.js +46 -21
- package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
- package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
- package/lib/helpers/populate/getSchemaTypes.js +27 -30
- package/lib/helpers/populate/getVirtual.js +31 -0
- package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
- package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
- package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
- package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
- package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
- package/lib/helpers/populate/splitPopulateQuery.js +81 -0
- package/lib/helpers/printJestWarning.js +1 -1
- package/lib/helpers/processConnectionOptions.js +7 -2
- package/lib/helpers/projection/applyProjection.js +8 -2
- package/lib/helpers/projection/hasIncludedChildren.js +1 -1
- package/lib/helpers/projection/isExclusive.js +8 -6
- package/lib/helpers/projection/isInclusive.js +2 -1
- package/lib/helpers/projection/isPathExcluded.js +3 -3
- package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
- package/lib/helpers/projection/isSubpath.js +1 -1
- package/lib/helpers/projection/parseProjection.js +9 -4
- package/lib/helpers/query/applyGlobalOption.js +9 -9
- package/lib/helpers/query/cast$expr.js +52 -23
- package/lib/helpers/query/castFilterPath.js +22 -22
- package/lib/helpers/query/castUpdate.js +207 -79
- package/lib/helpers/query/cloneMongooseOptions.js +44 -0
- package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
- package/lib/helpers/query/handleImmutable.js +18 -2
- package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
- package/lib/helpers/query/sanitizeFilter.js +3 -2
- package/lib/helpers/query/selectPopulatedFields.js +13 -0
- package/lib/helpers/query/validOps.js +1 -22
- package/lib/helpers/schema/applyPlugins.js +2 -2
- package/lib/helpers/schema/applyReadConcern.js +20 -0
- package/lib/helpers/schema/applyWriteConcern.js +12 -3
- package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
- package/lib/helpers/schema/getIndexes.js +20 -13
- package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
- package/lib/helpers/schema/getPath.js +11 -3
- package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
- package/lib/helpers/schema/handleIdOption.js +1 -1
- package/lib/helpers/schema/idGetter.js +7 -2
- package/lib/helpers/schema/merge.js +9 -1
- package/lib/helpers/schematype/getConditionalHandler.js +23 -0
- package/lib/helpers/schematype/handleImmutable.js +1 -1
- package/lib/helpers/setDefaultsOnInsert.js +85 -43
- package/lib/helpers/symbols.js +4 -4
- package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
- package/lib/helpers/timestamps/setupTimestamps.js +69 -37
- package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
- package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
- package/lib/helpers/update/castArrayFilters.js +68 -29
- package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
- package/lib/helpers/update/modifiedPaths.js +2 -2
- package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
- package/lib/helpers/updateValidators.js +87 -128
- package/lib/index.js +6 -1320
- package/lib/internal.js +7 -1
- package/lib/model.js +2587 -2618
- package/lib/modifiedPathsSnapshot.js +9 -0
- package/lib/mongoose.js +1456 -0
- package/lib/options/saveOptions.js +2 -0
- package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
- package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
- package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
- package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
- package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
- package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
- package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
- package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
- package/lib/options/schemaSubdocumentOptions.js +89 -0
- package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
- package/lib/options/schemaUnionOptions.js +32 -0
- package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
- package/lib/options.js +4 -1
- package/lib/plugins/index.js +0 -2
- package/lib/plugins/saveSubdocs.js +85 -50
- package/lib/plugins/sharding.js +43 -15
- package/lib/plugins/trackTransaction.js +46 -34
- package/lib/query.js +1844 -1909
- package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
- package/lib/schema/array.js +229 -169
- package/lib/schema/bigint.js +281 -0
- package/lib/schema/boolean.js +90 -26
- package/lib/schema/buffer.js +119 -50
- package/lib/schema/date.js +102 -38
- package/lib/schema/decimal128.js +88 -37
- package/lib/schema/{documentarray.js → documentArray.js} +259 -151
- package/lib/schema/documentArrayElement.js +180 -0
- package/lib/schema/double.js +244 -0
- package/lib/schema/index.js +12 -19
- package/lib/schema/int32.js +288 -0
- package/lib/schema/map.js +129 -20
- package/lib/schema/mixed.js +40 -26
- package/lib/schema/number.js +128 -51
- package/lib/schema/{objectid.js → objectId.js} +89 -47
- package/lib/schema/operators/exists.js +1 -1
- package/lib/schema/operators/geospatial.js +2 -2
- package/lib/schema/operators/text.js +4 -4
- package/lib/schema/string.js +125 -66
- package/lib/schema/subdocument.js +443 -0
- package/lib/schema/symbols.js +2 -0
- package/lib/schema/union.js +167 -0
- package/lib/schema/uuid.js +90 -120
- package/lib/schema.js +1267 -388
- package/lib/{schematype.js → schemaType.js} +481 -246
- package/lib/standardSchema/convertErrorToIssues.js +20 -0
- package/lib/{statemachine.js → stateMachine.js} +66 -17
- package/lib/tracing.js +38 -0
- package/lib/types/array/index.js +13 -10
- package/lib/types/array/methods/index.js +243 -63
- package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
- package/lib/types/buffer.js +31 -14
- package/lib/types/decimal128.js +1 -1
- package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
- package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
- package/lib/types/double.js +13 -0
- package/lib/types/index.js +5 -2
- package/lib/types/map.js +62 -25
- package/lib/types/objectid.js +2 -2
- package/lib/types/subdocument.js +79 -58
- package/lib/types/uuid.js +13 -0
- package/lib/utils.js +201 -155
- package/lib/{validoptions.js → validOptions.js} +10 -2
- package/lib/{virtualtype.js → virtualType.js} +47 -18
- package/package.json +75 -92
- package/types/aggregate.d.ts +31 -7
- package/types/augmentations.d.ts +2 -2
- package/types/collection.d.ts +21 -16
- package/types/connection.d.ts +82 -27
- package/types/cursor.d.ts +15 -10
- package/types/document.d.ts +137 -56
- package/types/error.d.ts +11 -6
- package/types/expressions.d.ts +33 -2
- package/types/index.d.ts +805 -190
- package/types/indexes.d.ts +85 -13
- package/types/inferhydrateddoctype.d.ts +151 -0
- package/types/inferrawdoctype.d.ts +201 -0
- package/types/inferschematype.d.ts +287 -128
- package/types/middlewares.d.ts +50 -7
- package/types/models.d.ts +1555 -268
- package/types/mongooseoptions.d.ts +56 -7
- package/types/pipelinestage.d.ts +42 -3
- package/types/populate.d.ts +63 -1
- package/types/query.d.ts +592 -255
- package/types/schemaoptions.d.ts +78 -12
- package/types/schematypes.d.ts +254 -65
- package/types/session.d.ts +0 -4
- package/types/tracing.d.ts +10 -0
- package/types/types.d.ts +25 -8
- package/types/utility.d.ts +329 -30
- package/types/validation.d.ts +19 -14
- package/types/virtuals.d.ts +10 -10
- package/.eslintrc.js +0 -232
- package/.mocharc.yml +0 -4
- package/browser.js +0 -8
- package/lgtm.yml +0 -12
- package/lib/browser.js +0 -158
- package/lib/browserDocument.js +0 -101
- package/lib/cursor/ChangeStream.js +0 -154
- package/lib/cursor/QueryCursor.js +0 -545
- package/lib/document_provider.js +0 -30
- package/lib/drivers/browser/ReadPreference.js +0 -7
- package/lib/drivers/browser/binary.js +0 -14
- package/lib/drivers/browser/decimal128.js +0 -7
- package/lib/drivers/browser/index.js +0 -16
- package/lib/drivers/browser/objectid.js +0 -29
- package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
- package/lib/drivers/node-mongodb-native/binary.js +0 -10
- package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
- package/lib/drivers/node-mongodb-native/objectid.js +0 -16
- package/lib/error/disconnected.js +0 -33
- package/lib/helpers/printStrictQueryWarning.js +0 -11
- package/lib/helpers/promiseOrCallback.js +0 -55
- package/lib/helpers/query/applyQueryMiddleware.js +0 -79
- package/lib/helpers/query/completeMany.js +0 -52
- package/lib/helpers/query/wrapThunk.js +0 -36
- package/lib/options/SchemaSubdocumentOptions.js +0 -42
- package/lib/options/removeOptions.js +0 -14
- package/lib/plugins/removeSubdocs.js +0 -31
- package/lib/plugins/validateBeforeSave.js +0 -45
- package/lib/promise_provider.js +0 -49
- package/lib/schema/DocumentArrayElement.js +0 -100
- package/lib/schema/SubdocumentPath.js +0 -369
- package/scripts/build-browser.js +0 -18
- package/scripts/create-tarball.js +0 -7
- package/scripts/generateSearch.js +0 -154
- package/scripts/tsc-diagnostics-check.js +0 -15
- package/tools/auth.js +0 -31
- package/tools/repl.js +0 -35
- package/tools/sharded.js +0 -46
- package/tsconfig.json +0 -9
- /package/lib/{connectionstate.js → connectionState.js} +0 -0
- /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
- /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
- /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
package/lib/connection.js
CHANGED
|
@@ -4,28 +4,35 @@
|
|
|
4
4
|
* Module dependencies.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
const ChangeStream = require('./cursor/
|
|
7
|
+
const ChangeStream = require('./cursor/changeStream');
|
|
8
8
|
const EventEmitter = require('events').EventEmitter;
|
|
9
9
|
const Schema = require('./schema');
|
|
10
|
-
const STATES = require('./
|
|
10
|
+
const STATES = require('./connectionState');
|
|
11
|
+
const MongooseBulkWriteError = require('./error/bulkWriteError');
|
|
11
12
|
const MongooseError = require('./error/index');
|
|
12
|
-
const DisconnectedError = require('./error/disconnected');
|
|
13
|
-
const SyncIndexesError = require('./error/syncIndexes');
|
|
14
|
-
const PromiseProvider = require('./promise_provider');
|
|
15
13
|
const ServerSelectionError = require('./error/serverSelection');
|
|
14
|
+
const SyncIndexesError = require('./error/syncIndexes');
|
|
16
15
|
const applyPlugins = require('./helpers/schema/applyPlugins');
|
|
16
|
+
const clone = require('./helpers/clone');
|
|
17
17
|
const driver = require('./driver');
|
|
18
|
-
const promiseOrCallback = require('./helpers/promiseOrCallback');
|
|
19
18
|
const get = require('./helpers/get');
|
|
19
|
+
const getDefaultBulkwriteResult = require('./helpers/getDefaultBulkwriteResult');
|
|
20
|
+
const getOwnProperty = require('./helpers/getOwnProperty');
|
|
20
21
|
const immediate = require('./helpers/immediate');
|
|
21
|
-
const mongodb = require('mongodb');
|
|
22
|
-
const pkg = require('../package.json');
|
|
23
22
|
const utils = require('./utils');
|
|
24
|
-
const
|
|
23
|
+
const CreateCollectionsError = require('./error/createCollectionsError');
|
|
24
|
+
const castBulkWrite = require('./helpers/model/castBulkWrite');
|
|
25
|
+
const { modelSymbol } = require('./helpers/symbols');
|
|
26
|
+
const isPromise = require('./helpers/isPromise');
|
|
27
|
+
const decorateBulkWriteResult = require('./helpers/model/decorateBulkWriteResult');
|
|
25
28
|
|
|
26
29
|
const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
|
|
27
30
|
const sessionNewDocuments = require('./helpers/symbols').sessionNewDocuments;
|
|
28
31
|
|
|
32
|
+
// Snapshot the native Date constructor to ensure both Date.now() and new Date() (and other Date methods)
|
|
33
|
+
// bypass timer mocks such as those set up by useFakeTimers().
|
|
34
|
+
const Date = globalThis.Date;
|
|
35
|
+
|
|
29
36
|
/**
|
|
30
37
|
* A list of authentication mechanisms that don't require a password for authentication.
|
|
31
38
|
* This is used by the authMechanismDoesNotRequirePassword method.
|
|
@@ -51,7 +58,8 @@ const noPasswordAuthMechanisms = [
|
|
|
51
58
|
* @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connection's models.
|
|
52
59
|
* @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection.
|
|
53
60
|
* @event `error`: Emitted when an error occurs on this connection.
|
|
54
|
-
* @event `
|
|
61
|
+
* @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.
|
|
62
|
+
* @event `operation-end`: Emitted when a call to the MongoDB Node.js driver, like a `find()` or `insertOne()`, either succeeds or errors.
|
|
55
63
|
* @api public
|
|
56
64
|
*/
|
|
57
65
|
|
|
@@ -74,6 +82,9 @@ function Connection(base) {
|
|
|
74
82
|
} else {
|
|
75
83
|
this.id = base.nextConnectionId;
|
|
76
84
|
}
|
|
85
|
+
|
|
86
|
+
// Internal queue of objects `{ fn, ctx, args }` that Mongoose calls when this connection is successfully
|
|
87
|
+
// opened. In `onOpen()`, Mongoose calls every entry in `_queue` and empties the queue.
|
|
77
88
|
this._queue = [];
|
|
78
89
|
}
|
|
79
90
|
|
|
@@ -106,11 +117,23 @@ Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype);
|
|
|
106
117
|
|
|
107
118
|
Object.defineProperty(Connection.prototype, 'readyState', {
|
|
108
119
|
get: function() {
|
|
120
|
+
// If connection thinks it is connected, but we haven't received a heartbeat in 2 heartbeat intervals,
|
|
121
|
+
// that likely means the connection is stale (potentially due to frozen AWS Lambda container)
|
|
122
|
+
if (
|
|
123
|
+
this._readyState === STATES.connected &&
|
|
124
|
+
this._lastHeartbeatAt != null &&
|
|
125
|
+
// LoadBalanced topology (behind haproxy, including Atlas serverless instances) don't use heartbeats,
|
|
126
|
+
// so we can't use this check in that case.
|
|
127
|
+
this.client?.topology?.s?.description?.type !== 'LoadBalanced' &&
|
|
128
|
+
typeof this.client?.topology?.s?.description?.heartbeatFrequencyMS === 'number' &&
|
|
129
|
+
Date.now() - this._lastHeartbeatAt >= this.client.topology.s.description.heartbeatFrequencyMS * 2) {
|
|
130
|
+
return STATES.disconnected;
|
|
131
|
+
}
|
|
109
132
|
return this._readyState;
|
|
110
133
|
},
|
|
111
134
|
set: function(val) {
|
|
112
135
|
if (!(val in STATES)) {
|
|
113
|
-
throw new
|
|
136
|
+
throw new MongooseError('Invalid connection state: ' + val);
|
|
114
137
|
}
|
|
115
138
|
|
|
116
139
|
if (this._readyState !== val) {
|
|
@@ -136,13 +159,13 @@ Object.defineProperty(Connection.prototype, 'readyState', {
|
|
|
136
159
|
*
|
|
137
160
|
* conn.get('test'); // returns the 'test' value
|
|
138
161
|
*
|
|
139
|
-
* @param {
|
|
162
|
+
* @param {string} key
|
|
140
163
|
* @method get
|
|
141
164
|
* @api public
|
|
142
165
|
*/
|
|
143
166
|
|
|
144
|
-
Connection.prototype.get = function(key) {
|
|
145
|
-
if (this.config
|
|
167
|
+
Connection.prototype.get = function getOption(key) {
|
|
168
|
+
if (Object.hasOwn(this.config, key)) {
|
|
146
169
|
return this.config[key];
|
|
147
170
|
}
|
|
148
171
|
|
|
@@ -154,8 +177,8 @@ Connection.prototype.get = function(key) {
|
|
|
154
177
|
*
|
|
155
178
|
* Supported options include:
|
|
156
179
|
*
|
|
157
|
-
* - `maxTimeMS`: Set [`maxTimeMS`](/docs/api/query.html#
|
|
158
|
-
* - '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
|
|
180
|
+
* - `maxTimeMS`: Set [`maxTimeMS`](https://mongoosejs.com/docs/api/query.html#Query.prototype.maxTimeMS()) for all queries on this connection.
|
|
181
|
+
* - '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 arguments 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(', ')})`.
|
|
159
182
|
*
|
|
160
183
|
* #### Example:
|
|
161
184
|
*
|
|
@@ -163,14 +186,14 @@ Connection.prototype.get = function(key) {
|
|
|
163
186
|
* conn.get('test'); // 'foo'
|
|
164
187
|
* conn.options.test; // 'foo'
|
|
165
188
|
*
|
|
166
|
-
* @param {
|
|
167
|
-
* @param {
|
|
189
|
+
* @param {string} key
|
|
190
|
+
* @param {any} val
|
|
168
191
|
* @method set
|
|
169
192
|
* @api public
|
|
170
193
|
*/
|
|
171
194
|
|
|
172
|
-
Connection.prototype.set = function(key, val) {
|
|
173
|
-
if (this.config
|
|
195
|
+
Connection.prototype.set = function setOption(key, val) {
|
|
196
|
+
if (Object.hasOwn(this.config, key)) {
|
|
174
197
|
this.config[key] = val;
|
|
175
198
|
return val;
|
|
176
199
|
}
|
|
@@ -209,7 +232,7 @@ Connection.prototype.name;
|
|
|
209
232
|
/**
|
|
210
233
|
* A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
|
|
211
234
|
* a map from model names to models. Contains all models that have been
|
|
212
|
-
* added to this connection using [`Connection#model()`](/docs/api/connection.html#
|
|
235
|
+
* added to this connection using [`Connection#model()`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.model()).
|
|
213
236
|
*
|
|
214
237
|
* #### Example:
|
|
215
238
|
*
|
|
@@ -229,7 +252,7 @@ Connection.prototype.models;
|
|
|
229
252
|
|
|
230
253
|
/**
|
|
231
254
|
* A number identifier for this connection. Used for debugging when
|
|
232
|
-
* you have [multiple connections](/docs/connections.html#multiple_connections).
|
|
255
|
+
* you have [multiple connections](https://mongoosejs.com/docs/connections.html#multiple_connections).
|
|
233
256
|
*
|
|
234
257
|
* #### Example:
|
|
235
258
|
*
|
|
@@ -388,26 +411,263 @@ Connection.prototype.config;
|
|
|
388
411
|
* with specified options. Used to create [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections/)
|
|
389
412
|
* and [views](https://www.mongodb.com/docs/manual/core/views/) from mongoose.
|
|
390
413
|
*
|
|
391
|
-
* Options are passed down without modification to the [MongoDB driver's `createCollection()` function](https://mongodb.github.io/node-mongodb-native/
|
|
414
|
+
* Options are passed down without modification to the [MongoDB driver's `createCollection()` function](https://mongodb.github.io/node-mongodb-native/7.0/classes/Db.html#createCollection)
|
|
392
415
|
*
|
|
393
416
|
* @method createCollection
|
|
394
417
|
* @param {string} collection The collection to create
|
|
395
|
-
* @param {
|
|
396
|
-
* @
|
|
397
|
-
* @return {Promise} Returns a Promise if no `callback` is given.
|
|
418
|
+
* @param {object} [options] see [MongoDB driver docs](https://mongodb.github.io/node-mongodb-native/7.0/classes/Db.html#createCollection)
|
|
419
|
+
* @return {Promise}
|
|
398
420
|
* @api public
|
|
399
421
|
*/
|
|
400
422
|
|
|
401
|
-
Connection.prototype.createCollection =
|
|
402
|
-
if (typeof options === 'function') {
|
|
403
|
-
|
|
404
|
-
options = {};
|
|
423
|
+
Connection.prototype.createCollection = async function createCollection(collection, options) {
|
|
424
|
+
if (typeof options === 'function' || (arguments.length >= 3 && typeof arguments[2] === 'function')) {
|
|
425
|
+
throw new MongooseError('Connection.prototype.createCollection() no longer accepts a callback');
|
|
405
426
|
}
|
|
406
|
-
|
|
407
|
-
|
|
427
|
+
|
|
428
|
+
await this._waitForConnect();
|
|
429
|
+
|
|
430
|
+
return this.db.createCollection(collection, options);
|
|
431
|
+
};
|
|
408
432
|
|
|
409
433
|
/**
|
|
410
|
-
* _Requires MongoDB
|
|
434
|
+
* _Requires MongoDB Server 8.0 or greater_. Executes bulk write operations across multiple models in a single operation.
|
|
435
|
+
* You must specify the `model` for each operation: Mongoose will use `model` for casting and validation, as well as
|
|
436
|
+
* determining which collection to apply the operation to.
|
|
437
|
+
*
|
|
438
|
+
* #### Example:
|
|
439
|
+
* const Test = mongoose.model('Test', new Schema({ name: String }));
|
|
440
|
+
*
|
|
441
|
+
* await db.bulkWrite([
|
|
442
|
+
* { model: Test, name: 'insertOne', document: { name: 'test1' } }, // Can specify model as a Model class...
|
|
443
|
+
* { model: 'Test', name: 'insertOne', document: { name: 'test2' } } // or as a model name
|
|
444
|
+
* ], { ordered: false });
|
|
445
|
+
*
|
|
446
|
+
* @method bulkWrite
|
|
447
|
+
* @param {Array} ops
|
|
448
|
+
* @param {object} [options]
|
|
449
|
+
* @param {boolean} [options.ordered] If false, perform unordered operations. If true, perform ordered operations.
|
|
450
|
+
* @param {Session} [options.session] The session to use for the operation.
|
|
451
|
+
* @return {Promise}
|
|
452
|
+
* @see MongoDB https://www.mongodb.com/docs/manual/reference/command/bulkWrite/#mongodb-dbcommand-dbcmd.bulkWrite
|
|
453
|
+
* @api public
|
|
454
|
+
*/
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
Connection.prototype.bulkWrite = async function bulkWrite(ops, options) {
|
|
458
|
+
await this._waitForConnect();
|
|
459
|
+
options = options || {};
|
|
460
|
+
|
|
461
|
+
const ordered = options.ordered == null ? true : options.ordered;
|
|
462
|
+
const asyncLocalStorage = this.base.transactionAsyncLocalStorage?.getStore();
|
|
463
|
+
if ((!options || !Object.hasOwn(options, 'session')) && asyncLocalStorage?.session != null) {
|
|
464
|
+
options = { ...options, session: asyncLocalStorage.session };
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const now = this.base.now();
|
|
468
|
+
|
|
469
|
+
let res = null;
|
|
470
|
+
if (ordered) {
|
|
471
|
+
const opsToSend = [];
|
|
472
|
+
for (const op of ops) {
|
|
473
|
+
if (typeof op.model !== 'string' && !op.model?.[modelSymbol]) {
|
|
474
|
+
throw new MongooseError('Must specify model in Connection.prototype.bulkWrite() operations');
|
|
475
|
+
}
|
|
476
|
+
const Model = op.model[modelSymbol] ? op.model : this.model(op.model);
|
|
477
|
+
|
|
478
|
+
if (op.name == null) {
|
|
479
|
+
throw new MongooseError('Must specify operation name in Connection.prototype.bulkWrite()');
|
|
480
|
+
}
|
|
481
|
+
if (!Object.hasOwn(castBulkWrite.cast, op.name)) {
|
|
482
|
+
throw new MongooseError(`Unrecognized bulkWrite() operation name ${op.name}`);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
await castBulkWrite.cast[op.name](Model, op, options, now);
|
|
486
|
+
opsToSend.push({ ...op, namespace: Model.namespace() });
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
res = await this.client.bulkWrite(opsToSend, options);
|
|
490
|
+
} else {
|
|
491
|
+
const validOps = [];
|
|
492
|
+
const validOpIndexes = [];
|
|
493
|
+
let validationErrors = [];
|
|
494
|
+
const asyncValidations = [];
|
|
495
|
+
const results = [];
|
|
496
|
+
for (let i = 0; i < ops.length; ++i) {
|
|
497
|
+
const op = ops[i];
|
|
498
|
+
if (typeof op.model !== 'string' && !op.model?.[modelSymbol]) {
|
|
499
|
+
const error = new MongooseError('Must specify model in Connection.prototype.bulkWrite() operations');
|
|
500
|
+
validationErrors.push({ index: i, error: error });
|
|
501
|
+
results[i] = error;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
let Model;
|
|
505
|
+
try {
|
|
506
|
+
Model = op.model[modelSymbol] ? op.model : this.model(op.model);
|
|
507
|
+
} catch (error) {
|
|
508
|
+
validationErrors.push({ index: i, error: error });
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (op.name == null) {
|
|
512
|
+
const error = new MongooseError('Must specify operation name in Connection.prototype.bulkWrite()');
|
|
513
|
+
validationErrors.push({ index: i, error: error });
|
|
514
|
+
results[i] = error;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (!Object.hasOwn(castBulkWrite.cast, op.name)) {
|
|
518
|
+
const error = new MongooseError(`Unrecognized bulkWrite() operation name ${op.name}`);
|
|
519
|
+
validationErrors.push({ index: i, error: error });
|
|
520
|
+
results[i] = error;
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
let maybePromise = null;
|
|
525
|
+
try {
|
|
526
|
+
maybePromise = castBulkWrite.cast[op.name](Model, op, options, now);
|
|
527
|
+
} catch (error) {
|
|
528
|
+
validationErrors.push({ index: i, error: error });
|
|
529
|
+
results[i] = error;
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
if (isPromise(maybePromise)) {
|
|
533
|
+
asyncValidations.push(
|
|
534
|
+
maybePromise.then(
|
|
535
|
+
() => {
|
|
536
|
+
validOps.push({ ...op, namespace: Model.namespace() });
|
|
537
|
+
validOpIndexes.push(i);
|
|
538
|
+
},
|
|
539
|
+
error => {
|
|
540
|
+
validationErrors.push({ index: i, error: error });
|
|
541
|
+
results[i] = error;
|
|
542
|
+
}
|
|
543
|
+
)
|
|
544
|
+
);
|
|
545
|
+
} else {
|
|
546
|
+
validOps.push({ ...op, namespace: Model.namespace() });
|
|
547
|
+
validOpIndexes.push(i);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (asyncValidations.length > 0) {
|
|
552
|
+
await Promise.all(asyncValidations);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
validationErrors = validationErrors.
|
|
556
|
+
sort((v1, v2) => v1.index - v2.index).
|
|
557
|
+
map(v => v.error);
|
|
558
|
+
|
|
559
|
+
if (validOps.length === 0) {
|
|
560
|
+
if (options.throwOnValidationError && validationErrors.length) {
|
|
561
|
+
throw new MongooseBulkWriteError(
|
|
562
|
+
validationErrors,
|
|
563
|
+
results,
|
|
564
|
+
res,
|
|
565
|
+
'bulkWrite'
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const BulkWriteResult = this.base.driver.get().BulkWriteResult;
|
|
569
|
+
const bulkWriteResult = new BulkWriteResult(getDefaultBulkwriteResult(), false);
|
|
570
|
+
return decorateBulkWriteResult(bulkWriteResult, validationErrors, results);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
let error;
|
|
574
|
+
[res, error] = await this.client.bulkWrite(validOps, options).
|
|
575
|
+
then(res => ([res, null])).
|
|
576
|
+
catch(err => ([null, err]));
|
|
577
|
+
|
|
578
|
+
for (let i = 0; i < validOpIndexes.length; ++i) {
|
|
579
|
+
results[validOpIndexes[i]] = null;
|
|
580
|
+
}
|
|
581
|
+
if (error) {
|
|
582
|
+
// client.bulkWrite() writeErrors is a Map keyed by index in validOps
|
|
583
|
+
error.writeErrors?.forEach((writeError, i) => {
|
|
584
|
+
results[validOpIndexes[i]] = writeError;
|
|
585
|
+
});
|
|
586
|
+
if (validationErrors.length > 0) {
|
|
587
|
+
decorateBulkWriteResult(error, validationErrors, results);
|
|
588
|
+
error.mongoose = error.mongoose || {};
|
|
589
|
+
error.mongoose.validationErrors = validationErrors;
|
|
590
|
+
}
|
|
591
|
+
throw error;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (validationErrors.length > 0) {
|
|
595
|
+
if (options.throwOnValidationError) {
|
|
596
|
+
throw new MongooseBulkWriteError(
|
|
597
|
+
validationErrors,
|
|
598
|
+
results,
|
|
599
|
+
res,
|
|
600
|
+
'bulkWrite'
|
|
601
|
+
);
|
|
602
|
+
} else {
|
|
603
|
+
decorateBulkWriteResult(res, validationErrors, results);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
return res;
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Calls `createCollection()` on a models in a series.
|
|
613
|
+
*
|
|
614
|
+
* @method createCollections
|
|
615
|
+
* @param {boolean} continueOnError When true, will continue to create collections and create a new error class for the collections that errored.
|
|
616
|
+
* @returns {Promise}
|
|
617
|
+
* @api public
|
|
618
|
+
*/
|
|
619
|
+
|
|
620
|
+
Connection.prototype.createCollections = async function createCollections(options = {}) {
|
|
621
|
+
const result = {};
|
|
622
|
+
const errorsMap = { };
|
|
623
|
+
|
|
624
|
+
const { continueOnError } = options;
|
|
625
|
+
delete options.continueOnError;
|
|
626
|
+
for (const model of Object.values(this.models)) {
|
|
627
|
+
try {
|
|
628
|
+
result[model.modelName] = await model.createCollection({});
|
|
629
|
+
} catch (err) {
|
|
630
|
+
if (!continueOnError) {
|
|
631
|
+
errorsMap[model.modelName] = err;
|
|
632
|
+
break;
|
|
633
|
+
} else {
|
|
634
|
+
result[model.modelName] = err;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
if (!continueOnError && utils.hasOwnKeys(errorsMap)) {
|
|
640
|
+
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
|
|
641
|
+
const createCollectionsError = new CreateCollectionsError(message, errorsMap);
|
|
642
|
+
throw createCollectionsError;
|
|
643
|
+
}
|
|
644
|
+
return result;
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* A convenience wrapper for `connection.client.withSession()`.
|
|
649
|
+
*
|
|
650
|
+
* #### Example:
|
|
651
|
+
*
|
|
652
|
+
* await conn.withSession(async session => {
|
|
653
|
+
* const doc = await TestModel.findOne().session(session);
|
|
654
|
+
* });
|
|
655
|
+
*
|
|
656
|
+
* @method withSession
|
|
657
|
+
* @param {Function} executor called with 1 argument: a `ClientSession` instance
|
|
658
|
+
* @return {Promise} resolves to the return value of the executor function
|
|
659
|
+
* @api public
|
|
660
|
+
*/
|
|
661
|
+
|
|
662
|
+
Connection.prototype.withSession = async function withSession(executor) {
|
|
663
|
+
if (arguments.length === 0) {
|
|
664
|
+
throw new MongooseError('Please provide an executor function');
|
|
665
|
+
}
|
|
666
|
+
return await this.client.withSession(executor);
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Starts a [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
|
|
411
671
|
* for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
|
|
412
672
|
* and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
|
|
413
673
|
*
|
|
@@ -415,7 +675,7 @@ Connection.prototype.createCollection = _wrapConnHelper(function createCollectio
|
|
|
415
675
|
*
|
|
416
676
|
* const session = await conn.startSession();
|
|
417
677
|
* let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
|
|
418
|
-
* await doc.
|
|
678
|
+
* await doc.deleteOne();
|
|
419
679
|
* // `doc` will always be null, even if reading from a replica set
|
|
420
680
|
* // secondary. Without causal consistency, it is possible to
|
|
421
681
|
* // get a doc back from the below query if the query reads from a
|
|
@@ -424,29 +684,30 @@ Connection.prototype.createCollection = _wrapConnHelper(function createCollectio
|
|
|
424
684
|
*
|
|
425
685
|
*
|
|
426
686
|
* @method startSession
|
|
427
|
-
* @param {
|
|
428
|
-
* @param {
|
|
429
|
-
* @param {Function} [callback]
|
|
687
|
+
* @param {object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html#startSession)
|
|
688
|
+
* @param {boolean} [options.causalConsistency=true] set to false to disable causal consistency
|
|
430
689
|
* @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
|
|
431
690
|
* @api public
|
|
432
691
|
*/
|
|
433
692
|
|
|
434
|
-
Connection.prototype.startSession =
|
|
435
|
-
if (typeof
|
|
436
|
-
|
|
437
|
-
options = null;
|
|
693
|
+
Connection.prototype.startSession = async function startSession(options) {
|
|
694
|
+
if (arguments.length >= 2 && typeof arguments[1] === 'function') {
|
|
695
|
+
throw new MongooseError('Connection.prototype.startSession() no longer accepts a callback');
|
|
438
696
|
}
|
|
697
|
+
|
|
698
|
+
await this._waitForConnect();
|
|
699
|
+
|
|
439
700
|
const session = this.client.startSession(options);
|
|
440
|
-
|
|
441
|
-
}
|
|
701
|
+
return session;
|
|
702
|
+
};
|
|
442
703
|
|
|
443
704
|
/**
|
|
444
|
-
*
|
|
705
|
+
* Executes the wrapped async function
|
|
445
706
|
* in a transaction. Mongoose will commit the transaction if the
|
|
446
707
|
* async function executes successfully and attempt to retry if
|
|
447
708
|
* there was a retriable error.
|
|
448
709
|
*
|
|
449
|
-
* Calls the MongoDB driver's [`session.withTransaction()`](https://mongodb.github.io/node-mongodb-native/
|
|
710
|
+
* Calls the MongoDB driver's [`session.withTransaction()`](https://mongodb.github.io/node-mongodb-native/7.0/classes/ClientSession.html#withTransaction),
|
|
450
711
|
* but also handles resetting Mongoose document state as shown below.
|
|
451
712
|
*
|
|
452
713
|
* #### Example:
|
|
@@ -458,7 +719,7 @@ Connection.prototype.startSession = _wrapConnHelper(function startSession(option
|
|
|
458
719
|
* doc.isNew; // false
|
|
459
720
|
*
|
|
460
721
|
* // Throw an error to abort the transaction
|
|
461
|
-
* throw new
|
|
722
|
+
* throw new MongooseError('Oops!');
|
|
462
723
|
* },{ readPreference: 'primary' }).catch(() => {});
|
|
463
724
|
*
|
|
464
725
|
* // true, `transaction()` reset the document's state because the
|
|
@@ -468,70 +729,204 @@ Connection.prototype.startSession = _wrapConnHelper(function startSession(option
|
|
|
468
729
|
* @method transaction
|
|
469
730
|
* @param {Function} fn Function to execute in a transaction
|
|
470
731
|
* @param {mongodb.TransactionOptions} [options] Optional settings for the transaction
|
|
471
|
-
* @return {Promise<
|
|
732
|
+
* @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.
|
|
472
733
|
* @api public
|
|
473
734
|
*/
|
|
474
735
|
|
|
475
736
|
Connection.prototype.transaction = function transaction(fn, options) {
|
|
476
737
|
return this.startSession().then(session => {
|
|
477
738
|
session[sessionNewDocuments] = new Map();
|
|
478
|
-
return session.withTransaction(() => fn
|
|
739
|
+
return session.withTransaction(() => _wrapUserTransaction(fn, session, this.base), options).
|
|
479
740
|
then(res => {
|
|
480
741
|
delete session[sessionNewDocuments];
|
|
481
742
|
return res;
|
|
482
743
|
}).
|
|
483
744
|
catch(err => {
|
|
484
|
-
// If transaction was aborted, we need to reset newly
|
|
485
|
-
// inserted documents' `isNew`.
|
|
486
|
-
for (const doc of session[sessionNewDocuments].keys()) {
|
|
487
|
-
const state = session[sessionNewDocuments].get(doc);
|
|
488
|
-
if (state.hasOwnProperty('isNew')) {
|
|
489
|
-
doc.$isNew = state.$isNew;
|
|
490
|
-
}
|
|
491
|
-
if (state.hasOwnProperty('versionKey')) {
|
|
492
|
-
doc.set(doc.schema.options.versionKey, state.versionKey);
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
if (state.modifiedPaths.length > 0 && doc.$__.activePaths.states.modify == null) {
|
|
496
|
-
doc.$__.activePaths.states.modify = {};
|
|
497
|
-
}
|
|
498
|
-
for (const path of state.modifiedPaths) {
|
|
499
|
-
doc.$__.activePaths.paths[path] = 'modify';
|
|
500
|
-
doc.$__.activePaths.states.modify[path] = true;
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
for (const path of state.atomics.keys()) {
|
|
504
|
-
const val = doc.$__getValue(path);
|
|
505
|
-
if (val == null) {
|
|
506
|
-
continue;
|
|
507
|
-
}
|
|
508
|
-
val[arrayAtomicsSymbol] = state.atomics.get(path);
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
745
|
delete session[sessionNewDocuments];
|
|
512
746
|
throw err;
|
|
513
|
-
})
|
|
514
|
-
|
|
515
|
-
session.endSession()
|
|
516
|
-
.catch(() => {});
|
|
747
|
+
}).
|
|
748
|
+
finally(() => {
|
|
749
|
+
session.endSession().catch(() => {});
|
|
517
750
|
});
|
|
518
751
|
});
|
|
519
752
|
};
|
|
520
753
|
|
|
754
|
+
/*!
|
|
755
|
+
* Reset document state in between transaction retries re: gh-13698
|
|
756
|
+
*/
|
|
757
|
+
|
|
758
|
+
async function _wrapUserTransaction(fn, session, mongoose) {
|
|
759
|
+
// `withTransaction()` also retries `fn` when `commitTransaction()` fails with a
|
|
760
|
+
// TransientTransactionError, which the `catch` below does not see. No-op on the first attempt.
|
|
761
|
+
_resetSessionDocuments(session);
|
|
762
|
+
try {
|
|
763
|
+
const res = mongoose.transactionAsyncLocalStorage == null
|
|
764
|
+
? await fn(session)
|
|
765
|
+
: await new Promise(resolve => {
|
|
766
|
+
mongoose.transactionAsyncLocalStorage.run(
|
|
767
|
+
{ session },
|
|
768
|
+
() => resolve(fn(session))
|
|
769
|
+
);
|
|
770
|
+
});
|
|
771
|
+
return res;
|
|
772
|
+
} catch (err) {
|
|
773
|
+
_resetSessionDocuments(session);
|
|
774
|
+
throw err;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/*!
|
|
779
|
+
* If transaction was aborted, we need to reset newly inserted documents' `isNew`.
|
|
780
|
+
*/
|
|
781
|
+
function _resetSessionDocuments(session) {
|
|
782
|
+
for (const doc of session[sessionNewDocuments].keys()) {
|
|
783
|
+
const state = session[sessionNewDocuments].get(doc);
|
|
784
|
+
if (Object.hasOwn(state, 'isNew')) {
|
|
785
|
+
doc.$isNew = state.isNew;
|
|
786
|
+
}
|
|
787
|
+
if (Object.hasOwn(state, 'versionKey')) {
|
|
788
|
+
doc.set(doc.schema.options.versionKey, state.versionKey);
|
|
789
|
+
}
|
|
790
|
+
if (Object.hasOwn(state, 'isDeleted')) {
|
|
791
|
+
doc.$isDeleted(state.isDeleted);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
for (const path of state.modifiedPaths) {
|
|
795
|
+
doc.$__.activePaths.modify(path);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
for (const path of state.atomics.keys()) {
|
|
799
|
+
const val = doc.$__getValue(path);
|
|
800
|
+
if (val == null) {
|
|
801
|
+
continue;
|
|
802
|
+
}
|
|
803
|
+
val[arrayAtomicsSymbol] = state.atomics.get(path);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
521
808
|
/**
|
|
522
809
|
* Helper for `dropCollection()`. Will delete the given collection, including
|
|
523
810
|
* all documents and indexes.
|
|
524
811
|
*
|
|
525
812
|
* @method dropCollection
|
|
526
813
|
* @param {string} collection The collection to delete
|
|
527
|
-
* @
|
|
528
|
-
* @return {Promise} Returns a Promise if no `callback` is given.
|
|
814
|
+
* @return {Promise}
|
|
529
815
|
* @api public
|
|
530
816
|
*/
|
|
531
817
|
|
|
532
|
-
Connection.prototype.dropCollection =
|
|
533
|
-
|
|
534
|
-
|
|
818
|
+
Connection.prototype.dropCollection = async function dropCollection(collection) {
|
|
819
|
+
if (arguments.length >= 2 && typeof arguments[1] === 'function') {
|
|
820
|
+
throw new MongooseError('Connection.prototype.dropCollection() no longer accepts a callback');
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
await this._waitForConnect();
|
|
824
|
+
|
|
825
|
+
return this.db.dropCollection(collection);
|
|
826
|
+
};
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* Waits for connection to be established, so the connection has a `client`
|
|
830
|
+
*
|
|
831
|
+
* @param {boolean} [noTimeout=false] if set, don't put a timeout on the operation. Used internally so `mongoose.model()` doesn't leave open handles.
|
|
832
|
+
* @return {Promise}
|
|
833
|
+
* @api private
|
|
834
|
+
*/
|
|
835
|
+
|
|
836
|
+
Connection.prototype._waitForConnect = async function _waitForConnect(noTimeout) {
|
|
837
|
+
if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
|
|
838
|
+
const bufferTimeoutMS = this._getBufferTimeoutMS();
|
|
839
|
+
let timeout = null;
|
|
840
|
+
let timedOut = false;
|
|
841
|
+
// The element that this function pushes onto `_queue`, stored to make it easy to remove later
|
|
842
|
+
const queueElement = {};
|
|
843
|
+
|
|
844
|
+
// Mongoose executes all elements in `_queue` when initial connection succeeds in `onOpen()`.
|
|
845
|
+
const waitForConnectPromise = new Promise(resolve => {
|
|
846
|
+
queueElement.fn = resolve;
|
|
847
|
+
this._queue.push(queueElement);
|
|
848
|
+
});
|
|
849
|
+
|
|
850
|
+
if (noTimeout) {
|
|
851
|
+
await waitForConnectPromise;
|
|
852
|
+
} else {
|
|
853
|
+
await Promise.race([
|
|
854
|
+
waitForConnectPromise,
|
|
855
|
+
new Promise(resolve => {
|
|
856
|
+
timeout = setTimeout(
|
|
857
|
+
() => {
|
|
858
|
+
timedOut = true;
|
|
859
|
+
resolve();
|
|
860
|
+
},
|
|
861
|
+
bufferTimeoutMS
|
|
862
|
+
);
|
|
863
|
+
})
|
|
864
|
+
]);
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
if (timedOut) {
|
|
868
|
+
const index = this._queue.indexOf(queueElement);
|
|
869
|
+
if (index !== -1) {
|
|
870
|
+
this._queue.splice(index, 1);
|
|
871
|
+
}
|
|
872
|
+
const message = 'Connection operation buffering timed out after ' + bufferTimeoutMS + 'ms';
|
|
873
|
+
throw new MongooseError(message);
|
|
874
|
+
} else if (timeout != null) {
|
|
875
|
+
// Not strictly necessary, but avoid the extra overhead of creating a new MongooseError
|
|
876
|
+
// in case of success
|
|
877
|
+
clearTimeout(timeout);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
/*!
|
|
883
|
+
* Get the default buffer timeout for this connection
|
|
884
|
+
*/
|
|
885
|
+
|
|
886
|
+
Connection.prototype._getBufferTimeoutMS = function _getBufferTimeoutMS() {
|
|
887
|
+
if (this.config.bufferTimeoutMS != null) {
|
|
888
|
+
return this.config.bufferTimeoutMS;
|
|
889
|
+
}
|
|
890
|
+
if (this.base?.get('bufferTimeoutMS') != null) {
|
|
891
|
+
return this.base.get('bufferTimeoutMS');
|
|
892
|
+
}
|
|
893
|
+
return 10000;
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Helper for MongoDB Node driver's `listCollections()`.
|
|
898
|
+
* Returns an array of collection objects.
|
|
899
|
+
*
|
|
900
|
+
* @method listCollections
|
|
901
|
+
* @return {Promise<Array<Collection>>}
|
|
902
|
+
* @api public
|
|
903
|
+
*/
|
|
904
|
+
|
|
905
|
+
Connection.prototype.listCollections = async function listCollections() {
|
|
906
|
+
await this._waitForConnect();
|
|
907
|
+
|
|
908
|
+
const cursor = this.db.listCollections();
|
|
909
|
+
return await cursor.toArray();
|
|
910
|
+
};
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Helper for MongoDB Node driver's `listDatabases()`.
|
|
914
|
+
* Returns an object with a `databases` property that contains an
|
|
915
|
+
* array of database objects.
|
|
916
|
+
*
|
|
917
|
+
* #### Example:
|
|
918
|
+
* const { databases } = await mongoose.connection.listDatabases();
|
|
919
|
+
* databases; // [{ name: 'mongoose_test', sizeOnDisk: 0, empty: false }]
|
|
920
|
+
*
|
|
921
|
+
* @method listCollections
|
|
922
|
+
* @return {Promise<Array<{ databases: { name: string } }>>}
|
|
923
|
+
* @api public
|
|
924
|
+
*/
|
|
925
|
+
|
|
926
|
+
Connection.prototype.listDatabases = async function listDatabases() {
|
|
927
|
+
// Implemented in `lib/drivers/node-mongodb-native/connection.js`
|
|
928
|
+
throw new MongooseError('listDatabases() not implemented by driver');
|
|
929
|
+
};
|
|
535
930
|
|
|
536
931
|
/**
|
|
537
932
|
* Helper for `dropDatabase()`. Deletes the given database, including all
|
|
@@ -544,12 +939,17 @@ Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(co
|
|
|
544
939
|
* await conn.dropDatabase();
|
|
545
940
|
*
|
|
546
941
|
* @method dropDatabase
|
|
547
|
-
* @
|
|
548
|
-
* @return {Promise} Returns a Promise if no `callback` is given.
|
|
942
|
+
* @return {Promise}
|
|
549
943
|
* @api public
|
|
550
944
|
*/
|
|
551
945
|
|
|
552
|
-
Connection.prototype.dropDatabase =
|
|
946
|
+
Connection.prototype.dropDatabase = async function dropDatabase() {
|
|
947
|
+
if (arguments.length >= 1 && typeof arguments[0] === 'function') {
|
|
948
|
+
throw new MongooseError('Connection.prototype.dropDatabase() no longer accepts a callback');
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
await this._waitForConnect();
|
|
952
|
+
|
|
553
953
|
// If `dropDatabase()` is called, this model's collection will not be
|
|
554
954
|
// init-ed. It is sufficiently common to call `dropDatabase()` after
|
|
555
955
|
// `mongoose.connect()` but before creating models that we want to
|
|
@@ -557,38 +957,9 @@ Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
|
|
|
557
957
|
for (const model of Object.values(this.models)) {
|
|
558
958
|
delete model.$init;
|
|
559
959
|
}
|
|
560
|
-
this.db.dropDatabase(cb);
|
|
561
|
-
});
|
|
562
|
-
|
|
563
|
-
/*!
|
|
564
|
-
* ignore
|
|
565
|
-
*/
|
|
566
960
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
|
|
570
|
-
const argsWithoutCb = typeof cb === 'function' ?
|
|
571
|
-
Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
|
|
572
|
-
Array.prototype.slice.call(arguments);
|
|
573
|
-
const disconnectedError = new DisconnectedError(this.id, fn.name);
|
|
574
|
-
|
|
575
|
-
return promiseOrCallback(cb, cb => {
|
|
576
|
-
immediate(() => {
|
|
577
|
-
if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
|
|
578
|
-
this._queue.push({ fn: fn, ctx: this, args: argsWithoutCb.concat([cb]) });
|
|
579
|
-
} else if (this.readyState === STATES.disconnected && this.db == null) {
|
|
580
|
-
cb(disconnectedError);
|
|
581
|
-
} else {
|
|
582
|
-
try {
|
|
583
|
-
fn.apply(this, argsWithoutCb.concat([cb]));
|
|
584
|
-
} catch (err) {
|
|
585
|
-
return cb(err);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
});
|
|
589
|
-
});
|
|
590
|
-
};
|
|
591
|
-
}
|
|
961
|
+
return this.db.dropDatabase();
|
|
962
|
+
};
|
|
592
963
|
|
|
593
964
|
/*!
|
|
594
965
|
* ignore
|
|
@@ -617,7 +988,7 @@ Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() {
|
|
|
617
988
|
* @api private
|
|
618
989
|
*/
|
|
619
990
|
|
|
620
|
-
Connection.prototype.error = function(err, callback) {
|
|
991
|
+
Connection.prototype.error = function error(err, callback) {
|
|
621
992
|
if (callback) {
|
|
622
993
|
callback(err);
|
|
623
994
|
return null;
|
|
@@ -631,21 +1002,19 @@ Connection.prototype.error = function(err, callback) {
|
|
|
631
1002
|
/**
|
|
632
1003
|
* Called when the connection is opened
|
|
633
1004
|
*
|
|
1005
|
+
* @emits "open"
|
|
634
1006
|
* @api private
|
|
635
1007
|
*/
|
|
636
1008
|
|
|
637
1009
|
Connection.prototype.onOpen = function() {
|
|
638
1010
|
this.readyState = STATES.connected;
|
|
639
1011
|
|
|
640
|
-
|
|
641
|
-
d.fn.apply(d.ctx, d.args);
|
|
642
|
-
}
|
|
643
|
-
this._queue = [];
|
|
1012
|
+
this._flushQueue();
|
|
644
1013
|
|
|
645
1014
|
// avoid having the collection subscribe to our event emitter
|
|
646
1015
|
// to prevent 0.3 warning
|
|
647
1016
|
for (const i in this.collections) {
|
|
648
|
-
if (
|
|
1017
|
+
if (Object.hasOwn(this.collections, i)) {
|
|
649
1018
|
this.collections[i].onOpen();
|
|
650
1019
|
}
|
|
651
1020
|
}
|
|
@@ -654,288 +1023,183 @@ Connection.prototype.onOpen = function() {
|
|
|
654
1023
|
};
|
|
655
1024
|
|
|
656
1025
|
/**
|
|
657
|
-
*
|
|
1026
|
+
* Flush all buffered operations in `_queue`. Called by `onOpen()` and
|
|
1027
|
+
* by the heartbeat handler when a previously-stale connection recovers.
|
|
658
1028
|
*
|
|
659
|
-
* @
|
|
660
|
-
* @param {Object} [options] Passed on to [`MongoClient.connect`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html#connect-1)
|
|
661
|
-
* @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.
|
|
662
|
-
* @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.
|
|
663
|
-
* @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
|
|
664
|
-
* @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
|
|
665
|
-
* @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
|
|
666
|
-
* @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).
|
|
667
|
-
* @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).
|
|
668
|
-
* @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).
|
|
669
|
-
* @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.
|
|
670
|
-
* @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
|
|
671
|
-
* @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/MongoClientOptions.html#promiseLibrary).
|
|
672
|
-
* @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
|
|
673
|
-
* @param {Number} [options.socketTimeoutMS=30000] 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. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. 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.
|
|
674
|
-
* @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.
|
|
675
|
-
* @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
|
|
676
|
-
* @param {Function} [callback]
|
|
677
|
-
* @returns {Promise<Connection>} Returns a Promise if no `callback` is given.
|
|
678
|
-
* @api public
|
|
1029
|
+
* @api private
|
|
679
1030
|
*/
|
|
680
1031
|
|
|
681
|
-
Connection.prototype.
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
if (['string', 'number'].indexOf(typeof options) !== -1) {
|
|
688
|
-
throw new MongooseError('Mongoose 5.x no longer supports ' +
|
|
689
|
-
'`mongoose.connect(host, dbname, port)` or ' +
|
|
690
|
-
'`mongoose.createConnection(host, dbname, port)`. See ' +
|
|
691
|
-
'https://mongoosejs.com/docs/connections.html for supported connection syntax');
|
|
692
|
-
}
|
|
693
|
-
|
|
694
|
-
if (typeof uri !== 'string') {
|
|
695
|
-
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
|
|
696
|
-
`string, got "${typeof uri}". Make sure the first parameter to ` +
|
|
697
|
-
'`mongoose.connect()` or `mongoose.createConnection()` is a string.');
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
if (callback != null && typeof callback !== 'function') {
|
|
701
|
-
throw new MongooseError('3rd parameter to `mongoose.connect()` or ' +
|
|
702
|
-
'`mongoose.createConnection()` must be a function, got "' +
|
|
703
|
-
typeof callback + '"');
|
|
1032
|
+
Connection.prototype._flushQueue = function _flushQueue() {
|
|
1033
|
+
const queue = this._queue;
|
|
1034
|
+
this._queue = [];
|
|
1035
|
+
for (const d of queue) {
|
|
1036
|
+
d.fn.apply(d.ctx, d.args);
|
|
704
1037
|
}
|
|
1038
|
+
};
|
|
705
1039
|
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
1040
|
+
/**
|
|
1041
|
+
* Opens the connection with a URI using `MongoClient.connect()`.
|
|
1042
|
+
*
|
|
1043
|
+
* @param {string} uri The URI to connect with.
|
|
1044
|
+
* @param {object} [options] Passed on to [`MongoClient.connect`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html#connect)
|
|
1045
|
+
* @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.
|
|
1046
|
+
* @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.
|
|
1047
|
+
* @param {string} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
|
|
1048
|
+
* @param {string} [options.user] username for authentication, equivalent to `options.auth.username`. Maintained for backwards compatibility.
|
|
1049
|
+
* @param {string} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
|
|
1050
|
+
* @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).
|
|
1051
|
+
* @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).
|
|
1052
|
+
* @param {number} [options.serverSelectionTimeoutMS] 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).
|
|
1053
|
+
* @param {number} [options.heartbeatFrequencyMS] 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.
|
|
1054
|
+
* @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
|
|
1055
|
+
* @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.
|
|
1056
|
+
* @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.
|
|
1057
|
+
* @param {boolean} [options.autoCreate=true] Set to `false` to disable Mongoose automatically calling `createCollection()` on every model created on this connection. Mongoose sets this option to `false` when `readPreference` is `secondary`, `secondaryPreferred`, or `nearest`. Setting `autoCreate: true` with `secondary` or `secondaryPreferred` throws an error.
|
|
1058
|
+
* @returns {Promise<Connection>}
|
|
1059
|
+
* @api public
|
|
1060
|
+
*/
|
|
717
1061
|
|
|
1062
|
+
Connection.prototype.openUri = async function openUri(uri, options) {
|
|
718
1063
|
if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
|
|
719
|
-
if (this._connectionString
|
|
720
|
-
|
|
721
|
-
'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' +
|
|
722
|
-
'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
if (typeof callback === 'function') {
|
|
726
|
-
this.$initialConnection = this.$initialConnection.then(
|
|
727
|
-
() => callback(null, this),
|
|
728
|
-
err => callback(err)
|
|
729
|
-
);
|
|
1064
|
+
if (this._connectionString === uri) {
|
|
1065
|
+
return this;
|
|
730
1066
|
}
|
|
731
|
-
return this;
|
|
732
1067
|
}
|
|
733
1068
|
|
|
734
|
-
this._connectionString = uri;
|
|
735
|
-
this.readyState = STATES.connecting;
|
|
736
1069
|
this._closeCalled = false;
|
|
737
1070
|
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
options
|
|
745
|
-
|
|
746
|
-
const autoIndex = options.config && options.config.autoIndex != null ?
|
|
747
|
-
options.config.autoIndex :
|
|
748
|
-
options.autoIndex;
|
|
749
|
-
if (autoIndex != null) {
|
|
750
|
-
this.config.autoIndex = autoIndex !== false;
|
|
751
|
-
delete options.config;
|
|
752
|
-
delete options.autoIndex;
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
if ('autoCreate' in options) {
|
|
756
|
-
this.config.autoCreate = !!options.autoCreate;
|
|
757
|
-
delete options.autoCreate;
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
if ('sanitizeFilter' in options) {
|
|
761
|
-
this.config.sanitizeFilter = options.sanitizeFilter;
|
|
762
|
-
delete options.sanitizeFilter;
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
// Backwards compat
|
|
766
|
-
if (options.user || options.pass) {
|
|
767
|
-
options.auth = options.auth || {};
|
|
768
|
-
options.auth.username = options.user;
|
|
769
|
-
options.auth.password = options.pass;
|
|
770
|
-
|
|
771
|
-
this.user = options.user;
|
|
772
|
-
this.pass = options.pass;
|
|
773
|
-
}
|
|
774
|
-
delete options.user;
|
|
775
|
-
delete options.pass;
|
|
776
|
-
|
|
777
|
-
if (options.bufferCommands != null) {
|
|
778
|
-
this.config.bufferCommands = options.bufferCommands;
|
|
779
|
-
delete options.bufferCommands;
|
|
780
|
-
}
|
|
781
|
-
} else {
|
|
782
|
-
options = {};
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
this._connectionOptions = options;
|
|
786
|
-
const dbName = options.dbName;
|
|
787
|
-
if (dbName != null) {
|
|
788
|
-
this.$dbName = dbName;
|
|
789
|
-
}
|
|
790
|
-
delete options.dbName;
|
|
791
|
-
|
|
792
|
-
if (!utils.hasUserDefinedProperty(options, 'driverInfo')) {
|
|
793
|
-
options.driverInfo = {
|
|
794
|
-
name: 'Mongoose',
|
|
795
|
-
version: pkg.version
|
|
796
|
-
};
|
|
1071
|
+
// Internal option to skip `await this.$initialConnection` in
|
|
1072
|
+
// this function for `createConnection()`. Because otherwise
|
|
1073
|
+
// `createConnection()` would have an uncatchable error.
|
|
1074
|
+
let _fireAndForget = false;
|
|
1075
|
+
if (options && '_fireAndForget' in options) {
|
|
1076
|
+
_fireAndForget = options._fireAndForget;
|
|
1077
|
+
delete options._fireAndForget;
|
|
797
1078
|
}
|
|
798
1079
|
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
_this.readyState = STATES.disconnected;
|
|
805
|
-
return reject(error);
|
|
1080
|
+
try {
|
|
1081
|
+
_validateArgs.apply(arguments);
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
if (_fireAndForget) {
|
|
1084
|
+
throw err;
|
|
806
1085
|
}
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
client.connect((error) => {
|
|
811
|
-
if (error) {
|
|
812
|
-
return reject(error);
|
|
813
|
-
}
|
|
814
|
-
|
|
815
|
-
_setClient(_this, client, options, dbName);
|
|
816
|
-
|
|
817
|
-
for (const db of this.otherDbs) {
|
|
818
|
-
_setClient(db, client, {}, db.name);
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
resolve(_this);
|
|
822
|
-
});
|
|
823
|
-
});
|
|
1086
|
+
this.$initialConnection = Promise.reject(err);
|
|
1087
|
+
throw err;
|
|
1088
|
+
}
|
|
824
1089
|
|
|
825
|
-
|
|
826
|
-
this.$initialConnection = promise.
|
|
1090
|
+
this.$initialConnection = this.createClient(uri, options).
|
|
827
1091
|
then(() => this).
|
|
828
1092
|
catch(err => {
|
|
829
1093
|
this.readyState = STATES.disconnected;
|
|
830
|
-
if (err != null && err.name === 'MongoServerSelectionError') {
|
|
831
|
-
err = serverSelectionError.assimilateError(err);
|
|
832
|
-
}
|
|
833
|
-
|
|
834
1094
|
if (this.listeners('error').length > 0) {
|
|
835
1095
|
immediate(() => this.emit('error', err));
|
|
836
1096
|
}
|
|
837
1097
|
throw err;
|
|
838
1098
|
});
|
|
839
1099
|
|
|
840
|
-
if (callback != null) {
|
|
841
|
-
this.$initialConnection = this.$initialConnection.then(
|
|
842
|
-
() => { callback(null, this); return this; },
|
|
843
|
-
err => callback(err)
|
|
844
|
-
);
|
|
845
|
-
}
|
|
846
|
-
|
|
847
1100
|
for (const model of Object.values(this.models)) {
|
|
848
1101
|
// Errors handled internally, so safe to ignore error
|
|
849
|
-
model.init(function $modelInitNoop() {});
|
|
1102
|
+
model.init().catch(function $modelInitNoop() {});
|
|
850
1103
|
}
|
|
851
1104
|
|
|
852
|
-
|
|
1105
|
+
// `createConnection()` calls this `openUri()` function without
|
|
1106
|
+
// awaiting on the result, so we set this option to rely on
|
|
1107
|
+
// `asPromise()` to handle any errors.
|
|
1108
|
+
if (_fireAndForget) {
|
|
1109
|
+
return this;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
try {
|
|
1113
|
+
await this.$initialConnection;
|
|
1114
|
+
} catch (err) {
|
|
1115
|
+
throw _handleConnectionErrors(err);
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
return this;
|
|
853
1119
|
};
|
|
854
1120
|
|
|
855
|
-
|
|
856
|
-
*
|
|
1121
|
+
/**
|
|
1122
|
+
* Listen to events in the Connection
|
|
1123
|
+
*
|
|
1124
|
+
* @param {string} event The event to listen on
|
|
1125
|
+
* @param {Function} callback
|
|
1126
|
+
* @see Connection#readyState https://mongoosejs.com/docs/api/connection.html#Connection.prototype.readyState
|
|
1127
|
+
*
|
|
1128
|
+
* @method on
|
|
1129
|
+
* @instance
|
|
1130
|
+
* @memberOf Connection
|
|
1131
|
+
* @api public
|
|
857
1132
|
*/
|
|
858
1133
|
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
client.s.options.hosts[0] &&
|
|
868
|
-
client.s.options.hosts[0].host || void 0;
|
|
869
|
-
conn.port = client &&
|
|
870
|
-
client.s &&
|
|
871
|
-
client.s.options &&
|
|
872
|
-
client.s.options.hosts &&
|
|
873
|
-
client.s.options.hosts[0] &&
|
|
874
|
-
client.s.options.hosts[0].port || void 0;
|
|
875
|
-
conn.name = dbName != null ? dbName : client && client.s && client.s.options && client.s.options.dbName || void 0;
|
|
876
|
-
conn._closeCalled = client._closeCalled;
|
|
877
|
-
|
|
878
|
-
const _handleReconnect = () => {
|
|
879
|
-
// If we aren't disconnected, we assume this reconnect is due to a
|
|
880
|
-
// socket timeout. If there's no activity on a socket for
|
|
881
|
-
// `socketTimeoutMS`, the driver will attempt to reconnect and emit
|
|
882
|
-
// this event.
|
|
883
|
-
if (conn.readyState !== STATES.connected) {
|
|
884
|
-
conn.readyState = STATES.connected;
|
|
885
|
-
conn.emit('reconnect');
|
|
886
|
-
conn.emit('reconnected');
|
|
887
|
-
conn.onOpen();
|
|
888
|
-
}
|
|
889
|
-
};
|
|
1134
|
+
// Treat `on('error')` handlers as handling the initialConnection promise
|
|
1135
|
+
// to avoid uncaught exceptions when using `on('error')`. See gh-14377.
|
|
1136
|
+
Connection.prototype.on = function on(event, callback) {
|
|
1137
|
+
if (event === 'error' && this.$initialConnection) {
|
|
1138
|
+
this.$initialConnection.catch(() => {});
|
|
1139
|
+
}
|
|
1140
|
+
return EventEmitter.prototype.on.call(this, event, callback);
|
|
1141
|
+
};
|
|
890
1142
|
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
1143
|
+
/**
|
|
1144
|
+
* Listen to a event once in the Connection
|
|
1145
|
+
*
|
|
1146
|
+
* @param {string} event The event to listen on
|
|
1147
|
+
* @param {Function} callback
|
|
1148
|
+
* @see Connection#readyState https://mongoosejs.com/docs/api/connection.html#Connection.prototype.readyState
|
|
1149
|
+
*
|
|
1150
|
+
* @method once
|
|
1151
|
+
* @instance
|
|
1152
|
+
* @memberOf Connection
|
|
1153
|
+
* @api public
|
|
1154
|
+
*/
|
|
895
1155
|
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
} else {
|
|
902
|
-
_handleReconnect();
|
|
903
|
-
}
|
|
904
|
-
});
|
|
905
|
-
} else if (type.startsWith('ReplicaSet')) {
|
|
906
|
-
client.on('topologyDescriptionChanged', ev => {
|
|
907
|
-
// Emit disconnected if we've lost connectivity to the primary
|
|
908
|
-
const description = ev.newDescription;
|
|
909
|
-
if (conn.readyState === STATES.connected && description.type !== 'ReplicaSetWithPrimary') {
|
|
910
|
-
// Implicitly emits 'disconnected'
|
|
911
|
-
conn.readyState = STATES.disconnected;
|
|
912
|
-
} else if (conn.readyState === STATES.disconnected && description.type === 'ReplicaSetWithPrimary') {
|
|
913
|
-
_handleReconnect();
|
|
914
|
-
}
|
|
915
|
-
});
|
|
1156
|
+
// Treat `on('error')` handlers as handling the initialConnection promise
|
|
1157
|
+
// to avoid uncaught exceptions when using `on('error')`. See gh-14377.
|
|
1158
|
+
Connection.prototype.once = function on(event, callback) {
|
|
1159
|
+
if (event === 'error' && this.$initialConnection) {
|
|
1160
|
+
this.$initialConnection.catch(() => {});
|
|
916
1161
|
}
|
|
1162
|
+
return EventEmitter.prototype.once.call(this, event, callback);
|
|
1163
|
+
};
|
|
917
1164
|
|
|
918
|
-
|
|
1165
|
+
/*!
|
|
1166
|
+
* ignore
|
|
1167
|
+
*/
|
|
919
1168
|
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1169
|
+
function _validateArgs(uri, options, callback) {
|
|
1170
|
+
if (typeof options === 'function' && callback == null) {
|
|
1171
|
+
throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
|
|
1172
|
+
} else if (typeof callback === 'function') {
|
|
1173
|
+
throw new MongooseError('Connection.prototype.openUri() no longer accepts a callback');
|
|
924
1174
|
}
|
|
925
1175
|
}
|
|
926
1176
|
|
|
1177
|
+
/*!
|
|
1178
|
+
* ignore
|
|
1179
|
+
*/
|
|
1180
|
+
|
|
1181
|
+
function _handleConnectionErrors(err) {
|
|
1182
|
+
if (err?.name === 'MongoServerSelectionError') {
|
|
1183
|
+
const originalError = err;
|
|
1184
|
+
err = new ServerSelectionError();
|
|
1185
|
+
err.assimilateError(originalError);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
return err;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
927
1191
|
/**
|
|
928
|
-
*
|
|
1192
|
+
* Destroy the connection. Similar to [`.close`](https://mongoosejs.com/docs/api/connection.html#Connection.prototype.close()),
|
|
1193
|
+
* but also removes the connection from Mongoose's `connections` list and prevents the
|
|
1194
|
+
* connection from ever being re-opened.
|
|
929
1195
|
*
|
|
930
|
-
* @param {
|
|
931
|
-
* @
|
|
932
|
-
* @returns {Promise} Returns a Promise if no `callback` is given.
|
|
1196
|
+
* @param {boolean} [force]
|
|
1197
|
+
* @returns {Promise}
|
|
933
1198
|
*/
|
|
934
1199
|
|
|
935
|
-
Connection.prototype.destroy = function(force
|
|
936
|
-
if (typeof force === 'function') {
|
|
937
|
-
|
|
938
|
-
force = false;
|
|
1200
|
+
Connection.prototype.destroy = async function destroy(force) {
|
|
1201
|
+
if (typeof force === 'function' || (arguments.length === 2 && typeof arguments[1] === 'function')) {
|
|
1202
|
+
throw new MongooseError('Connection.prototype.destroy() no longer accepts a callback');
|
|
939
1203
|
}
|
|
940
1204
|
|
|
941
1205
|
if (force != null && typeof force === 'object') {
|
|
@@ -944,24 +1208,20 @@ Connection.prototype.destroy = function(force, callback) {
|
|
|
944
1208
|
this.$wasForceClosed = !!force;
|
|
945
1209
|
}
|
|
946
1210
|
|
|
947
|
-
return
|
|
948
|
-
this._close(force, true, cb);
|
|
949
|
-
});
|
|
1211
|
+
return this._close(force, true);
|
|
950
1212
|
};
|
|
951
1213
|
|
|
952
1214
|
/**
|
|
953
1215
|
* Closes the connection
|
|
954
1216
|
*
|
|
955
|
-
* @param {
|
|
956
|
-
* @
|
|
957
|
-
* @return {Promise} Returns a Promise if no `callback` is given.
|
|
1217
|
+
* @param {boolean} [force] optional
|
|
1218
|
+
* @return {Promise}
|
|
958
1219
|
* @api public
|
|
959
1220
|
*/
|
|
960
1221
|
|
|
961
|
-
Connection.prototype.close = function(force
|
|
962
|
-
if (typeof force === 'function') {
|
|
963
|
-
|
|
964
|
-
force = false;
|
|
1222
|
+
Connection.prototype.close = async function close(force) {
|
|
1223
|
+
if (typeof force === 'function' || (arguments.length === 2 && typeof arguments[1] === 'function')) {
|
|
1224
|
+
throw new MongooseError('Connection.prototype.close() no longer accepts a callback');
|
|
965
1225
|
}
|
|
966
1226
|
|
|
967
1227
|
if (force != null && typeof force === 'object') {
|
|
@@ -970,6 +1230,10 @@ Connection.prototype.close = function(force, callback) {
|
|
|
970
1230
|
this.$wasForceClosed = !!force;
|
|
971
1231
|
}
|
|
972
1232
|
|
|
1233
|
+
if (this._lastHeartbeatAt != null) {
|
|
1234
|
+
this._lastHeartbeatAt = null;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
973
1237
|
for (const model of Object.values(this.models)) {
|
|
974
1238
|
// If manually disconnecting, make sure to clear each model's `$init`
|
|
975
1239
|
// promise, so Mongoose knows to re-run `init()` in case the
|
|
@@ -977,21 +1241,18 @@ Connection.prototype.close = function(force, callback) {
|
|
|
977
1241
|
delete model.$init;
|
|
978
1242
|
}
|
|
979
1243
|
|
|
980
|
-
return
|
|
981
|
-
this._close(force, false, cb);
|
|
982
|
-
});
|
|
1244
|
+
return this._close(force, false);
|
|
983
1245
|
};
|
|
984
1246
|
|
|
985
1247
|
/**
|
|
986
1248
|
* Handles closing the connection
|
|
987
1249
|
*
|
|
988
|
-
* @param {
|
|
989
|
-
* @param {
|
|
990
|
-
* @param {Function} [callback]
|
|
1250
|
+
* @param {boolean} force
|
|
1251
|
+
* @param {boolean} destroy
|
|
991
1252
|
* @returns {Connection} this
|
|
992
1253
|
* @api private
|
|
993
1254
|
*/
|
|
994
|
-
Connection.prototype._close = function(force, destroy
|
|
1255
|
+
Connection.prototype._close = async function _close(force, destroy) {
|
|
995
1256
|
const _this = this;
|
|
996
1257
|
const closeCalled = this._closeCalled;
|
|
997
1258
|
this._closeCalled = true;
|
|
@@ -1004,50 +1265,55 @@ Connection.prototype._close = function(force, destroy, callback) {
|
|
|
1004
1265
|
const conn = this;
|
|
1005
1266
|
switch (this.readyState) {
|
|
1006
1267
|
case STATES.disconnected:
|
|
1007
|
-
if (destroy
|
|
1008
|
-
this.base.connections.
|
|
1268
|
+
if (destroy) {
|
|
1269
|
+
const index = this.base.connections.indexOf(conn);
|
|
1270
|
+
if (index !== -1) {
|
|
1271
|
+
this.base.connections.splice(index, 1);
|
|
1272
|
+
}
|
|
1009
1273
|
}
|
|
1010
|
-
if (closeCalled) {
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
this.doClose(force, function(err) {
|
|
1014
|
-
if (err) {
|
|
1015
|
-
return callback(err);
|
|
1016
|
-
}
|
|
1017
|
-
_this.onClose(force);
|
|
1018
|
-
callback(null);
|
|
1019
|
-
});
|
|
1274
|
+
if (!closeCalled) {
|
|
1275
|
+
await this.doClose(force);
|
|
1276
|
+
this.onClose(force);
|
|
1020
1277
|
}
|
|
1021
1278
|
break;
|
|
1022
1279
|
|
|
1023
1280
|
case STATES.connected:
|
|
1024
1281
|
this.readyState = STATES.disconnecting;
|
|
1025
|
-
this.doClose(force
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
_this.base.connections.splice(_this.base.connections.indexOf(conn), 1);
|
|
1282
|
+
await this.doClose(force);
|
|
1283
|
+
if (destroy) {
|
|
1284
|
+
const index = _this.base.connections.indexOf(conn);
|
|
1285
|
+
if (index !== -1) {
|
|
1286
|
+
this.base.connections.splice(index, 1);
|
|
1031
1287
|
}
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
});
|
|
1288
|
+
}
|
|
1289
|
+
this.onClose(force);
|
|
1035
1290
|
|
|
1036
1291
|
break;
|
|
1037
1292
|
case STATES.connecting:
|
|
1038
|
-
|
|
1039
|
-
|
|
1293
|
+
return new Promise((resolve, reject) => {
|
|
1294
|
+
const _rerunClose = () => {
|
|
1295
|
+
this.removeListener('open', _rerunClose);
|
|
1296
|
+
this.removeListener('error', _rerunClose);
|
|
1297
|
+
if (destroy) {
|
|
1298
|
+
this.destroy(force).then(resolve, reject);
|
|
1299
|
+
} else {
|
|
1300
|
+
this.close(force).then(resolve, reject);
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
|
|
1304
|
+
this.once('open', _rerunClose);
|
|
1305
|
+
this.once('error', _rerunClose);
|
|
1040
1306
|
});
|
|
1041
|
-
break;
|
|
1042
1307
|
|
|
1043
1308
|
case STATES.disconnecting:
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1309
|
+
return new Promise(resolve => {
|
|
1310
|
+
this.once('close', () => {
|
|
1311
|
+
if (destroy && this.base.connections.indexOf(conn) !== -1) {
|
|
1312
|
+
this.base.connections.splice(this.base.connections.indexOf(conn), 1);
|
|
1313
|
+
}
|
|
1314
|
+
resolve();
|
|
1315
|
+
});
|
|
1049
1316
|
});
|
|
1050
|
-
break;
|
|
1051
1317
|
}
|
|
1052
1318
|
|
|
1053
1319
|
return this;
|
|
@@ -1059,53 +1325,58 @@ Connection.prototype._close = function(force, destroy, callback) {
|
|
|
1059
1325
|
* @api private
|
|
1060
1326
|
*/
|
|
1061
1327
|
|
|
1062
|
-
Connection.prototype.doClose = function() {
|
|
1063
|
-
throw new
|
|
1328
|
+
Connection.prototype.doClose = function doClose() {
|
|
1329
|
+
throw new MongooseError('Connection#doClose unimplemented by driver');
|
|
1064
1330
|
};
|
|
1065
1331
|
|
|
1066
1332
|
/**
|
|
1067
1333
|
* Called when the connection closes
|
|
1068
1334
|
*
|
|
1335
|
+
* @emits "close"
|
|
1069
1336
|
* @api private
|
|
1070
1337
|
*/
|
|
1071
1338
|
|
|
1072
|
-
Connection.prototype.onClose = function(force) {
|
|
1339
|
+
Connection.prototype.onClose = function onClose(force) {
|
|
1073
1340
|
this.readyState = STATES.disconnected;
|
|
1074
1341
|
|
|
1075
1342
|
// avoid having the collection subscribe to our event emitter
|
|
1076
1343
|
// to prevent 0.3 warning
|
|
1077
1344
|
for (const i in this.collections) {
|
|
1078
|
-
if (
|
|
1345
|
+
if (Object.hasOwn(this.collections, i)) {
|
|
1079
1346
|
this.collections[i].onClose(force);
|
|
1080
1347
|
}
|
|
1081
1348
|
}
|
|
1082
1349
|
|
|
1083
1350
|
this.emit('close', force);
|
|
1084
1351
|
|
|
1352
|
+
const wasForceClosed = typeof force === 'object' && force !== null ? force.force : force;
|
|
1353
|
+
|
|
1085
1354
|
for (const db of this.otherDbs) {
|
|
1086
|
-
this._destroyCalled ? db.destroy({ force:
|
|
1355
|
+
this._destroyCalled ? db.destroy({ force: wasForceClosed, skipCloseClient: true }) : db.close({ force: wasForceClosed, skipCloseClient: true });
|
|
1087
1356
|
}
|
|
1088
1357
|
};
|
|
1089
1358
|
|
|
1090
1359
|
/**
|
|
1091
|
-
* Retrieves a collection, creating it if not cached.
|
|
1092
|
-
*
|
|
1093
|
-
*
|
|
1360
|
+
* Retrieves a raw collection instance, creating it if not cached.
|
|
1361
|
+
* This method returns a thin wrapper around a [MongoDB Node.js driver collection](https://mongodb.github.io/node-mongodb-native/Next/classes/Collection.html).
|
|
1362
|
+
* Using a Collection bypasses Mongoose middleware, validation, and casting,
|
|
1363
|
+
* letting you use [MongoDB Node.js driver](https://mongodb.github.io/node-mongodb-native/) functionality directly.
|
|
1094
1364
|
*
|
|
1095
|
-
* @param {
|
|
1096
|
-
* @param {
|
|
1365
|
+
* @param {string} name of the collection
|
|
1366
|
+
* @param {object} [options] optional collection options
|
|
1097
1367
|
* @return {Collection} collection instance
|
|
1098
1368
|
* @api public
|
|
1099
1369
|
*/
|
|
1100
1370
|
|
|
1101
1371
|
Connection.prototype.collection = function(name, options) {
|
|
1102
1372
|
const defaultOptions = {
|
|
1103
|
-
autoIndex: this.config.autoIndex
|
|
1104
|
-
autoCreate: this.config.autoCreate
|
|
1373
|
+
autoIndex: this.config.autoIndex ?? this.base.options.autoIndex,
|
|
1374
|
+
autoCreate: this.config.autoCreate ?? this.base.options.autoCreate,
|
|
1375
|
+
autoSearchIndex: this.config.autoSearchIndex ?? this.base.options.autoSearchIndex
|
|
1105
1376
|
};
|
|
1106
|
-
options = Object.assign({}, defaultOptions, options ?
|
|
1377
|
+
options = Object.assign({}, defaultOptions, options ? clone(options) : {});
|
|
1107
1378
|
options.$wasForceClosed = this.$wasForceClosed;
|
|
1108
|
-
const Collection = this.base
|
|
1379
|
+
const Collection = this.base?.__driver?.Collection || driver.get().Collection;
|
|
1109
1380
|
if (!(name in this.collections)) {
|
|
1110
1381
|
this.collections[name] = new Collection(name, this, options);
|
|
1111
1382
|
}
|
|
@@ -1126,9 +1397,9 @@ Connection.prototype.collection = function(name, options) {
|
|
|
1126
1397
|
* db.model('Test', new Schema({})); // Prints "Applied"
|
|
1127
1398
|
*
|
|
1128
1399
|
* @param {Function} fn plugin callback
|
|
1129
|
-
* @param {
|
|
1400
|
+
* @param {object} [opts] optional options
|
|
1130
1401
|
* @return {Connection} this
|
|
1131
|
-
* @see plugins /docs/plugins.html
|
|
1402
|
+
* @see plugins https://mongoosejs.com/docs/plugins.html
|
|
1132
1403
|
* @api public
|
|
1133
1404
|
*/
|
|
1134
1405
|
|
|
@@ -1146,7 +1417,7 @@ Connection.prototype.plugin = function(fn, opts) {
|
|
|
1146
1417
|
* const Ticket = db.model('Ticket', new Schema(..));
|
|
1147
1418
|
* const Venue = db.model('Venue');
|
|
1148
1419
|
*
|
|
1149
|
-
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the
|
|
1420
|
+
* _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the `utils.toCollectionName` method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
|
|
1150
1421
|
*
|
|
1151
1422
|
* #### Example:
|
|
1152
1423
|
*
|
|
@@ -1161,17 +1432,17 @@ Connection.prototype.plugin = function(fn, opts) {
|
|
|
1161
1432
|
* const collectionName = 'actor'
|
|
1162
1433
|
* const M = conn.model('Actor', schema, collectionName)
|
|
1163
1434
|
*
|
|
1164
|
-
* @param {
|
|
1435
|
+
* @param {string|Function} name the model name or class extending Model
|
|
1165
1436
|
* @param {Schema} [schema] a schema. necessary when defining a model
|
|
1166
|
-
* @param {
|
|
1167
|
-
* @param {
|
|
1168
|
-
* @param {
|
|
1169
|
-
* @see Mongoose#model #
|
|
1437
|
+
* @param {string} [collection] name of mongodb collection (optional) if not given it will be induced from model name
|
|
1438
|
+
* @param {object} [options]
|
|
1439
|
+
* @param {boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError`
|
|
1440
|
+
* @see Mongoose#model https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.model()
|
|
1170
1441
|
* @return {Model} The compiled model
|
|
1171
1442
|
* @api public
|
|
1172
1443
|
*/
|
|
1173
1444
|
|
|
1174
|
-
Connection.prototype.model = function(name, schema, collection, options) {
|
|
1445
|
+
Connection.prototype.model = function model(name, schema, collection, options) {
|
|
1175
1446
|
if (!(this instanceof Connection)) {
|
|
1176
1447
|
throw new MongooseError('`connection.model()` should not be run with ' +
|
|
1177
1448
|
'`new`. If you are doing `new db.model(foo)(bar)`, use ' +
|
|
@@ -1198,23 +1469,25 @@ Connection.prototype.model = function(name, schema, collection, options) {
|
|
|
1198
1469
|
}
|
|
1199
1470
|
}
|
|
1200
1471
|
if (schema && !schema.instanceOfSchema) {
|
|
1201
|
-
throw new
|
|
1472
|
+
throw new MongooseError('The 2nd parameter to `mongoose.model()` should be a ' +
|
|
1202
1473
|
'schema or a POJO');
|
|
1203
1474
|
}
|
|
1204
1475
|
|
|
1205
1476
|
const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels };
|
|
1206
1477
|
const opts = Object.assign(defaultOptions, options, { connection: this });
|
|
1207
|
-
|
|
1478
|
+
// Own properties only, so names like 'constructor' or 'toString' don't return built-ins
|
|
1479
|
+
const existingModel = getOwnProperty(this.models, name);
|
|
1480
|
+
if (existingModel && !collection && opts.overwriteModels !== true) {
|
|
1208
1481
|
// model exists but we are not subclassing with custom collection
|
|
1209
|
-
if (schema
|
|
1482
|
+
if (schema?.instanceOfSchema && schema !== existingModel.schema) {
|
|
1210
1483
|
throw new MongooseError.OverwriteModelError(name);
|
|
1211
1484
|
}
|
|
1212
|
-
return
|
|
1485
|
+
return existingModel;
|
|
1213
1486
|
}
|
|
1214
1487
|
|
|
1215
1488
|
let model;
|
|
1216
1489
|
|
|
1217
|
-
if (schema
|
|
1490
|
+
if (schema?.instanceOfSchema) {
|
|
1218
1491
|
applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied');
|
|
1219
1492
|
|
|
1220
1493
|
// compile a model
|
|
@@ -1222,19 +1495,19 @@ Connection.prototype.model = function(name, schema, collection, options) {
|
|
|
1222
1495
|
|
|
1223
1496
|
// only the first model with this name is cached to allow
|
|
1224
1497
|
// for one-offs with custom collection names etc.
|
|
1225
|
-
if (!this.models
|
|
1498
|
+
if (!getOwnProperty(this.models, name)) {
|
|
1226
1499
|
this.models[name] = model;
|
|
1227
1500
|
}
|
|
1228
1501
|
|
|
1229
1502
|
// Errors handled internally, so safe to ignore error
|
|
1230
|
-
model.init(function $modelInitNoop() {});
|
|
1503
|
+
model.init().catch(function $modelInitNoop() {});
|
|
1231
1504
|
|
|
1232
1505
|
return model;
|
|
1233
1506
|
}
|
|
1234
1507
|
|
|
1235
|
-
if (
|
|
1508
|
+
if (existingModel && collection) {
|
|
1236
1509
|
// subclassing current model with alternate collection
|
|
1237
|
-
model =
|
|
1510
|
+
model = existingModel;
|
|
1238
1511
|
schema = model.prototype.schema;
|
|
1239
1512
|
const sub = model.__subclass(this, schema, collection);
|
|
1240
1513
|
// do not cache the sub model
|
|
@@ -1242,7 +1515,7 @@ Connection.prototype.model = function(name, schema, collection, options) {
|
|
|
1242
1515
|
}
|
|
1243
1516
|
|
|
1244
1517
|
if (arguments.length === 1) {
|
|
1245
|
-
model =
|
|
1518
|
+
model = existingModel;
|
|
1246
1519
|
if (!model) {
|
|
1247
1520
|
throw new MongooseError.MissingSchemaError(name);
|
|
1248
1521
|
}
|
|
@@ -1287,11 +1560,11 @@ Connection.prototype.model = function(name, schema, collection, options) {
|
|
|
1287
1560
|
* });
|
|
1288
1561
|
*
|
|
1289
1562
|
* @api public
|
|
1290
|
-
* @param {
|
|
1563
|
+
* @param {string|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
|
|
1291
1564
|
* @return {Connection} this
|
|
1292
1565
|
*/
|
|
1293
1566
|
|
|
1294
|
-
Connection.prototype.deleteModel = function(name) {
|
|
1567
|
+
Connection.prototype.deleteModel = function deleteModel(name) {
|
|
1295
1568
|
if (typeof name === 'string') {
|
|
1296
1569
|
const model = this.model(name);
|
|
1297
1570
|
if (model == null) {
|
|
@@ -1311,7 +1584,7 @@ Connection.prototype.deleteModel = function(name) {
|
|
|
1311
1584
|
}
|
|
1312
1585
|
}
|
|
1313
1586
|
} else {
|
|
1314
|
-
throw new
|
|
1587
|
+
throw new MongooseError('First parameter to `deleteModel()` must be a string ' +
|
|
1315
1588
|
'or regexp, got "' + name + '"');
|
|
1316
1589
|
}
|
|
1317
1590
|
|
|
@@ -1320,7 +1593,7 @@ Connection.prototype.deleteModel = function(name) {
|
|
|
1320
1593
|
|
|
1321
1594
|
/**
|
|
1322
1595
|
* Watches the entire underlying database for changes. Similar to
|
|
1323
|
-
* [`Model.watch()`](/docs/api/model.html#
|
|
1596
|
+
* [`Model.watch()`](https://mongoosejs.com/docs/api/model.html#Model.watch()).
|
|
1324
1597
|
*
|
|
1325
1598
|
* This function does **not** trigger any middleware. In particular, it
|
|
1326
1599
|
* does **not** trigger aggregate middleware.
|
|
@@ -1343,31 +1616,14 @@ Connection.prototype.deleteModel = function(name) {
|
|
|
1343
1616
|
*
|
|
1344
1617
|
* @api public
|
|
1345
1618
|
* @param {Array} [pipeline]
|
|
1346
|
-
* @param {
|
|
1619
|
+
* @param {object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/7.0/classes/Db.html#watch)
|
|
1347
1620
|
* @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter
|
|
1348
1621
|
*/
|
|
1349
1622
|
|
|
1350
|
-
Connection.prototype.watch = function(pipeline, options) {
|
|
1351
|
-
const
|
|
1352
|
-
|
|
1353
|
-
const changeStreamThunk = cb => {
|
|
1354
|
-
immediate(() => {
|
|
1355
|
-
if (this.readyState === STATES.connecting) {
|
|
1356
|
-
this.once('open', function() {
|
|
1357
|
-
const driverChangeStream = this.db.watch(pipeline, options);
|
|
1358
|
-
cb(null, driverChangeStream);
|
|
1359
|
-
});
|
|
1360
|
-
} else if (this.readyState === STATES.disconnected && this.db == null) {
|
|
1361
|
-
cb(disconnectedError);
|
|
1362
|
-
} else {
|
|
1363
|
-
const driverChangeStream = this.db.watch(pipeline, options);
|
|
1364
|
-
cb(null, driverChangeStream);
|
|
1365
|
-
}
|
|
1366
|
-
});
|
|
1367
|
-
};
|
|
1623
|
+
Connection.prototype.watch = function watch(pipeline, options) {
|
|
1624
|
+
const changeStreamPromise = this._waitForConnect().then(() => this.db.watch(pipeline, options));
|
|
1368
1625
|
|
|
1369
|
-
|
|
1370
|
-
return changeStream;
|
|
1626
|
+
return new ChangeStream(changeStreamPromise, pipeline, options);
|
|
1371
1627
|
};
|
|
1372
1628
|
|
|
1373
1629
|
/**
|
|
@@ -1385,17 +1641,22 @@ Connection.prototype.watch = function(pipeline, options) {
|
|
|
1385
1641
|
* @return {Promise}
|
|
1386
1642
|
*/
|
|
1387
1643
|
|
|
1388
|
-
Connection.prototype.asPromise = function asPromise() {
|
|
1389
|
-
|
|
1644
|
+
Connection.prototype.asPromise = async function asPromise() {
|
|
1645
|
+
try {
|
|
1646
|
+
await this.$initialConnection;
|
|
1647
|
+
return this;
|
|
1648
|
+
} catch (err) {
|
|
1649
|
+
throw _handleConnectionErrors(err);
|
|
1650
|
+
}
|
|
1390
1651
|
};
|
|
1391
1652
|
|
|
1392
1653
|
/**
|
|
1393
1654
|
* Returns an array of model names created on this connection.
|
|
1394
1655
|
* @api public
|
|
1395
|
-
* @return {
|
|
1656
|
+
* @return {Array<string>}
|
|
1396
1657
|
*/
|
|
1397
1658
|
|
|
1398
|
-
Connection.prototype.modelNames = function() {
|
|
1659
|
+
Connection.prototype.modelNames = function modelNames() {
|
|
1399
1660
|
return Object.keys(this.models);
|
|
1400
1661
|
};
|
|
1401
1662
|
|
|
@@ -1405,9 +1666,9 @@ Connection.prototype.modelNames = function() {
|
|
|
1405
1666
|
* password is not required.
|
|
1406
1667
|
*
|
|
1407
1668
|
* @api private
|
|
1408
|
-
* @return {
|
|
1669
|
+
* @return {boolean} true if the connection should be authenticated after it is opened, otherwise false.
|
|
1409
1670
|
*/
|
|
1410
|
-
Connection.prototype.shouldAuthenticate = function() {
|
|
1671
|
+
Connection.prototype.shouldAuthenticate = function shouldAuthenticate() {
|
|
1411
1672
|
return this.user != null &&
|
|
1412
1673
|
(this.pass != null || this.authMechanismDoesNotRequirePassword());
|
|
1413
1674
|
};
|
|
@@ -1417,11 +1678,11 @@ Connection.prototype.shouldAuthenticate = function() {
|
|
|
1417
1678
|
* password to authenticate according to the auth objects passed into the openUri methods.
|
|
1418
1679
|
*
|
|
1419
1680
|
* @api private
|
|
1420
|
-
* @return {
|
|
1681
|
+
* @return {boolean} true if the authentication mechanism specified in the options object requires
|
|
1421
1682
|
* a password, otherwise false.
|
|
1422
1683
|
*/
|
|
1423
|
-
Connection.prototype.authMechanismDoesNotRequirePassword = function() {
|
|
1424
|
-
if (this.options
|
|
1684
|
+
Connection.prototype.authMechanismDoesNotRequirePassword = function authMechanismDoesNotRequirePassword() {
|
|
1685
|
+
if (this.options?.auth) {
|
|
1425
1686
|
return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
|
|
1426
1687
|
}
|
|
1427
1688
|
return true;
|
|
@@ -1433,19 +1694,19 @@ Connection.prototype.authMechanismDoesNotRequirePassword = function() {
|
|
|
1433
1694
|
* but in some authentication methods, a password is not required for authentication so only a username
|
|
1434
1695
|
* is required.
|
|
1435
1696
|
*
|
|
1436
|
-
* @param {
|
|
1697
|
+
* @param {object} [options] the options object passed into the openUri methods.
|
|
1437
1698
|
* @api private
|
|
1438
|
-
* @return {
|
|
1699
|
+
* @return {boolean} true if the provided options object provides enough data to authenticate with,
|
|
1439
1700
|
* otherwise false.
|
|
1440
1701
|
*/
|
|
1441
|
-
Connection.prototype.optionsProvideAuthenticationData = function(options) {
|
|
1702
|
+
Connection.prototype.optionsProvideAuthenticationData = function optionsProvideAuthenticationData(options) {
|
|
1442
1703
|
return (options) &&
|
|
1443
1704
|
(options.user) &&
|
|
1444
1705
|
((options.pass) || this.authMechanismDoesNotRequirePassword());
|
|
1445
1706
|
};
|
|
1446
1707
|
|
|
1447
1708
|
/**
|
|
1448
|
-
* Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/
|
|
1709
|
+
* Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
|
|
1449
1710
|
* that this connection uses to talk to MongoDB.
|
|
1450
1711
|
*
|
|
1451
1712
|
* #### Example:
|
|
@@ -1464,7 +1725,7 @@ Connection.prototype.getClient = function getClient() {
|
|
|
1464
1725
|
};
|
|
1465
1726
|
|
|
1466
1727
|
/**
|
|
1467
|
-
* Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/
|
|
1728
|
+
* Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html) instance
|
|
1468
1729
|
* that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
|
|
1469
1730
|
* reuse it.
|
|
1470
1731
|
*
|
|
@@ -1482,34 +1743,24 @@ Connection.prototype.getClient = function getClient() {
|
|
|
1482
1743
|
* @return {Connection} this
|
|
1483
1744
|
*/
|
|
1484
1745
|
|
|
1485
|
-
Connection.prototype.setClient = function setClient(
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
}
|
|
1489
|
-
if (this.readyState !== STATES.disconnected) {
|
|
1490
|
-
throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');
|
|
1491
|
-
}
|
|
1492
|
-
if (client.topology == null) {
|
|
1493
|
-
throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.');
|
|
1494
|
-
}
|
|
1495
|
-
|
|
1496
|
-
this._connectionString = client.s.url;
|
|
1497
|
-
_setClient(this, client, {}, client.s.options.dbName);
|
|
1746
|
+
Connection.prototype.setClient = function setClient() {
|
|
1747
|
+
throw new MongooseError('Connection#setClient not implemented by driver');
|
|
1748
|
+
};
|
|
1498
1749
|
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
}
|
|
1750
|
+
/*!
|
|
1751
|
+
* Called internally by `openUri()` to create a MongoClient instance.
|
|
1752
|
+
*/
|
|
1503
1753
|
|
|
1504
|
-
|
|
1754
|
+
Connection.prototype.createClient = function createClient() {
|
|
1755
|
+
throw new MongooseError('Connection#createClient not implemented by driver');
|
|
1505
1756
|
};
|
|
1506
1757
|
|
|
1507
1758
|
/**
|
|
1508
1759
|
* Syncs all the indexes for the models registered with this connection.
|
|
1509
1760
|
*
|
|
1510
|
-
* @param {
|
|
1511
|
-
* @param {
|
|
1512
|
-
* @return {Promise<
|
|
1761
|
+
* @param {object} [options]
|
|
1762
|
+
* @param {boolean} [options.continueOnError] `false` by default. If set to `true`, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
|
|
1763
|
+
* @return {Promise<object>} Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.
|
|
1513
1764
|
*/
|
|
1514
1765
|
Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
|
|
1515
1766
|
const result = {};
|
|
@@ -1531,7 +1782,7 @@ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
|
|
|
1531
1782
|
}
|
|
1532
1783
|
}
|
|
1533
1784
|
|
|
1534
|
-
if (!continueOnError &&
|
|
1785
|
+
if (!continueOnError && utils.hasOwnKeys(errorsMap)) {
|
|
1535
1786
|
const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
|
|
1536
1787
|
const syncIndexesError = new SyncIndexesError(message, errorsMap);
|
|
1537
1788
|
throw syncIndexesError;
|
|
@@ -1541,7 +1792,7 @@ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
|
|
|
1541
1792
|
};
|
|
1542
1793
|
|
|
1543
1794
|
/**
|
|
1544
|
-
* Switches to a different database using the same connection pool.
|
|
1795
|
+
* Switches to a different database using the same [connection pool](https://mongoosejs.com/docs/connections.html#connection_pools).
|
|
1545
1796
|
*
|
|
1546
1797
|
* Returns a new connection object, with the new db.
|
|
1547
1798
|
*
|
|
@@ -1558,14 +1809,48 @@ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
|
|
|
1558
1809
|
*
|
|
1559
1810
|
* @method useDb
|
|
1560
1811
|
* @memberOf Connection
|
|
1561
|
-
* @param {
|
|
1562
|
-
* @param {
|
|
1563
|
-
* @param {
|
|
1564
|
-
* @param {Boolean} [options.noListener=false] If true, the connection object will not make the db listen to events on the original connection. See [issue #9961](https://github.com/Automattic/mongoose/issues/9961).
|
|
1812
|
+
* @param {string} name The database name
|
|
1813
|
+
* @param {object} [options]
|
|
1814
|
+
* @param {boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
|
|
1565
1815
|
* @return {Connection} New Connection Object
|
|
1566
1816
|
* @api public
|
|
1567
1817
|
*/
|
|
1568
1818
|
|
|
1819
|
+
/**
|
|
1820
|
+
* Runs a [db-level aggregate()](https://www.mongodb.com/docs/manual/reference/method/db.aggregate/) on this connection's underlying `db`
|
|
1821
|
+
*
|
|
1822
|
+
* @method aggregate
|
|
1823
|
+
* @memberOf Connection
|
|
1824
|
+
* @param {Array} pipeline
|
|
1825
|
+
* @param {object} [options]
|
|
1826
|
+
* @param {boolean} [options.cursor=false] If true, make the Aggregate resolve to a Mongoose AggregationCursor rather than an array
|
|
1827
|
+
* @return {Aggregate} Aggregation wrapper
|
|
1828
|
+
* @api public
|
|
1829
|
+
*/
|
|
1830
|
+
|
|
1831
|
+
/**
|
|
1832
|
+
* Removes the database connection with the given name created with `useDb()`.
|
|
1833
|
+
*
|
|
1834
|
+
* Throws an error if the database connection was not found.
|
|
1835
|
+
*
|
|
1836
|
+
* #### Example:
|
|
1837
|
+
*
|
|
1838
|
+
* // Connect to `initialdb` first
|
|
1839
|
+
* const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/initialdb').asPromise();
|
|
1840
|
+
*
|
|
1841
|
+
* // Creates an un-cached connection to `mydb`
|
|
1842
|
+
* const db = conn.useDb('mydb');
|
|
1843
|
+
*
|
|
1844
|
+
* // Closes `db`, and removes `db` from `conn.relatedDbs` and `conn.otherDbs`
|
|
1845
|
+
* await conn.removeDb('mydb');
|
|
1846
|
+
*
|
|
1847
|
+
* @method removeDb
|
|
1848
|
+
* @memberOf Connection
|
|
1849
|
+
* @param {string} name The database name
|
|
1850
|
+
* @return {Connection} this
|
|
1851
|
+
* @api public
|
|
1852
|
+
*/
|
|
1853
|
+
|
|
1569
1854
|
/*!
|
|
1570
1855
|
* Module exports.
|
|
1571
1856
|
*/
|