@datanimbus/mongoose 6.13.13 → 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.
Files changed (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
@@ -0,0 +1,1456 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const Document = require('./document');
8
+ const EventEmitter = require('events').EventEmitter;
9
+ const Kareem = require('kareem');
10
+ const Schema = require('./schema');
11
+ const SchemaType = require('./schemaType');
12
+ const SchemaTypes = require('./schema/index');
13
+ const VirtualType = require('./virtualType');
14
+ const STATES = require('./connectionState');
15
+ const VALID_OPTIONS = require('./validOptions');
16
+ const Types = require('./types');
17
+ const Query = require('./query');
18
+ const Model = require('./model');
19
+ const applyPlugins = require('./helpers/schema/applyPlugins');
20
+ const builtinPlugins = require('./plugins');
21
+ const driver = require('./driver');
22
+ const legacyPluralize = require('./helpers/pluralize');
23
+ const utils = require('./utils');
24
+ const pkg = require('../package.json');
25
+ const cast = require('./cast');
26
+
27
+ const Aggregate = require('./aggregate');
28
+ const trusted = require('./helpers/query/trusted').trusted;
29
+ const sanitizeFilter = require('./helpers/query/sanitizeFilter');
30
+ const isBsonType = require('./helpers/isBsonType');
31
+ const getOwnProperty = require('./helpers/getOwnProperty');
32
+ const MongooseError = require('./error/mongooseError');
33
+ const SetOptionError = require('./error/setOptionError');
34
+ const applyEmbeddedDiscriminators = require('./helpers/discriminator/applyEmbeddedDiscriminators');
35
+
36
+ const defaultMongooseSymbol = Symbol.for('mongoose:default');
37
+ const defaultConnectionSymbol = Symbol('mongoose:defaultConnection');
38
+
39
+ require('./helpers/printJestWarning');
40
+
41
+ const objectIdHexRegexp = /^[0-9A-Fa-f]{24}$/;
42
+
43
+ const { AsyncLocalStorage } = require('async_hooks');
44
+
45
+ /**
46
+ * Mongoose constructor.
47
+ *
48
+ * The exports object of the `mongoose` module is an instance of this class.
49
+ * Most apps will only use this one instance.
50
+ *
51
+ * #### Example:
52
+ *
53
+ * const mongoose = require('mongoose');
54
+ * mongoose instanceof mongoose.Mongoose; // true
55
+ *
56
+ * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
57
+ * const m = new mongoose.Mongoose();
58
+ *
59
+ * @api public
60
+ * @param {object} options see [`Mongoose#set()` docs](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.set())
61
+ */
62
+ function Mongoose(options) {
63
+ this.connections = [];
64
+ this.nextConnectionId = 0;
65
+ this.models = {};
66
+ this.events = new EventEmitter();
67
+ this.__driver = driver.get();
68
+ // default global options
69
+ this.options = Object.assign({
70
+ pluralization: true,
71
+ autoIndex: true,
72
+ autoCreate: true,
73
+ autoSearchIndex: false
74
+ }, options);
75
+ const createInitialConnection = utils.getOption('createInitialConnection', this.options) ?? true;
76
+ if (createInitialConnection && this.__driver != null) {
77
+ _createDefaultConnection(this);
78
+ }
79
+
80
+ if (this.options.pluralization) {
81
+ this._pluralize = legacyPluralize;
82
+ }
83
+
84
+ // If a user creates their own Mongoose instance, give them a separate copy
85
+ // of the `Schema` constructor so they get separate custom types. (gh-6933)
86
+ if (!options?.[defaultMongooseSymbol]) {
87
+ const _this = this;
88
+ this.Schema = function() {
89
+ this.base = _this;
90
+ return Schema.apply(this, arguments);
91
+ };
92
+ this.Schema.prototype = Object.create(Schema.prototype);
93
+
94
+ Object.assign(this.Schema, Schema);
95
+ this.Schema.base = this;
96
+ this.Schema.Types = Object.assign({}, Schema.Types);
97
+ } else {
98
+ // Hack to work around babel's strange behavior with
99
+ // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not
100
+ // an own property of a Mongoose global, Schema will be undefined. See gh-5648
101
+ for (const key of ['Schema', 'model']) {
102
+ this[key] = Mongoose.prototype[key];
103
+ }
104
+ }
105
+ this.Schema.prototype.base = this;
106
+
107
+ if (options?.transactionAsyncLocalStorage) {
108
+ this.transactionAsyncLocalStorage = new AsyncLocalStorage();
109
+ }
110
+
111
+ Object.defineProperty(this, 'plugins', {
112
+ configurable: false,
113
+ enumerable: true,
114
+ writable: false,
115
+ value: Object.values(builtinPlugins).map(plugin => ([plugin, { deduplicate: true }]))
116
+ });
117
+ }
118
+
119
+ Mongoose.prototype.cast = cast;
120
+ /**
121
+ * Expose connection states for user-land
122
+ *
123
+ * @memberOf Mongoose
124
+ * @property STATES
125
+ * @api public
126
+ */
127
+ Mongoose.prototype.STATES = STATES;
128
+
129
+ /**
130
+ * Expose connection states for user-land
131
+ *
132
+ * @memberOf Mongoose
133
+ * @property ConnectionStates
134
+ * @api public
135
+ */
136
+ Mongoose.prototype.ConnectionStates = STATES;
137
+
138
+ /**
139
+ * Object with `get()` and `set()` containing the underlying driver this Mongoose instance
140
+ * uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions
141
+ * like `find()`.
142
+ *
143
+ * @deprecated
144
+ * @memberOf Mongoose
145
+ * @property driver
146
+ * @api public
147
+ */
148
+
149
+ Mongoose.prototype.driver = driver;
150
+
151
+ /**
152
+ * Overwrites the current driver used by this Mongoose instance. A driver is a
153
+ * Mongoose-specific interface that defines functions like `find()`.
154
+ *
155
+ * @memberOf Mongoose
156
+ * @method setDriver
157
+ * @api public
158
+ */
159
+
160
+ Mongoose.prototype.setDriver = function setDriver(driver) {
161
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
162
+
163
+ if (_mongoose.__driver === driver) {
164
+ return _mongoose;
165
+ }
166
+
167
+ const openConnection = _mongoose.connections && _mongoose.connections.find(conn => conn.readyState !== STATES.disconnected);
168
+ if (openConnection) {
169
+ const msg = 'Cannot modify Mongoose driver if a connection is already open. ' +
170
+ 'Call `mongoose.disconnect()` before modifying the driver';
171
+ throw new MongooseError(msg);
172
+ }
173
+ _mongoose.__driver = driver;
174
+
175
+ if (Array.isArray(driver.plugins)) {
176
+ for (const plugin of driver.plugins) {
177
+ if (typeof plugin === 'function') {
178
+ _mongoose.plugin(plugin);
179
+ }
180
+ }
181
+ }
182
+
183
+ if (driver.SchemaTypes != null) {
184
+ Object.assign(mongoose.Schema.Types, driver.SchemaTypes);
185
+ }
186
+
187
+ const Connection = driver.Connection;
188
+ const oldDefaultConnection = _mongoose.connections[0];
189
+ _mongoose.connections = [new Connection(_mongoose)];
190
+ _mongoose.connections[0].models = _mongoose.models;
191
+ if (oldDefaultConnection == null) {
192
+ return _mongoose;
193
+ }
194
+
195
+ // Update all models that pointed to the old default connection to
196
+ // the new default connection, including collections
197
+ for (const model of Object.values(_mongoose.models)) {
198
+ if (model.db !== oldDefaultConnection) {
199
+ continue;
200
+ }
201
+ model.$__updateConnection(_mongoose.connections[0]);
202
+ }
203
+
204
+ return _mongoose;
205
+ };
206
+
207
+ /**
208
+ * Sets mongoose options
209
+ *
210
+ * `key` can be used as an object to set multiple options at once.
211
+ * If an error gets thrown for one option, other options will still be evaluated.
212
+ *
213
+ * #### Example:
214
+ *
215
+ * mongoose.set('test', value) // sets the 'test' option to `value`
216
+ *
217
+ * mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file
218
+ *
219
+ * mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments
220
+ *
221
+ * mongoose.set({ debug: true, autoIndex: false }); // set multiple options at once
222
+ *
223
+ * Currently supported options are:
224
+ * - `allowDiskUse`: Set to `true` to set `allowDiskUse` to true to all aggregation operations by default.
225
+ * - `applyPluginsToChildSchemas`: `true` by default. Set to `false` to skip applying global plugins to child schemas
226
+ * - `applyPluginsToDiscriminators`: `false` by default. Set to `true` to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
227
+ * - `autoCreate`: `true` by default. Mongoose calls [`Model.createCollection()`](https://mongoosejs.com/docs/api/model.html#Model.createCollection()) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist. Set to `false` to disable this behavior. Connections with `readPreference` set to `secondary`, `secondaryPreferred`, or `nearest` disable `autoCreate`.
228
+ * - `autoIndex`: `true` by default. Set to `false` to disable automatic index creation for all models associated with this Mongoose instance.
229
+ * - `autoSearchIndex`: `false` by default. Set to `true` to automatically create [Atlas search indexes](https://mongoosejs.com/docs/guide.html#autoSearchIndex) defined in your schemas.
230
+ * - `bufferCommands`: enable/disable mongoose's buffering mechanism for all connections and models
231
+ * - `bufferTimeoutMS`: If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
232
+ * - `cloneSchemas`: `false` by default. Set to `true` to `clone()` all schemas before compiling into a model.
233
+ * - `createInitialConnection`: `true` by default. Set to `false` to disable the creation of the initial default connection. If the default connection already exists, Mongoose removes it only if it is disconnected and has no models.
234
+ * - `debug`: If `true`, prints the operations mongoose sends to MongoDB to the console. If an object is passed, you can set `color`, `shell`, and `timestamp` options. If `timestamp` is `true`, Mongoose prefixes console debug output with an ISO timestamp in brackets. 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(', ')})`.
235
+ * - `forceRepopulate`: `true` by default. Set to `false` to prevent `populate()` from repopulating paths that are already populated.
236
+ * - `id`: If `true`, adds a `id` virtual to all schemas unless overwritten on a per-schema basis.
237
+ * - `maxTimeMS`: If set, attaches [maxTimeMS](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/) to every query
238
+ * - `objectIdGetter`: `true` by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to `false` to remove the getter.
239
+ * - `overwriteModels`: Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`.
240
+ * - `returnDocument`: Set to `'before'` or `'after'` to set the default value for the `returnDocument` option to `findOneAndUpdate()`, `findByIdAndUpdate()`, and `findOneAndReplace()`. Defaults to `'before'`, which returns the document before the update was applied. Read our [`findOneAndUpdate()` tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html) for more information.
241
+ * - `returnOriginal`: **Deprecated.** Use `returnDocument` instead. If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html) for more information.
242
+ * - `runValidators`: `false` by default. Set to `true` to enable [update validators](https://mongoosejs.com/docs/validation.html#update-validators) for all validators by default.
243
+ * - `sanitizeFilter`: `false` by default. Set to `true` to enable the [sanitization of the query filters](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.sanitizeFilter()) against query selector injection attacks by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`.
244
+ * - `sanitizeProjection`: `false` by default. Set to `true` to enable [`sanitizeProjection`](https://mongoosejs.com/docs/api/query.html#Query.prototype.sanitizeProjection()) on all queries.
245
+ * - `selectPopulatedPaths`: `true` by default. Set to `false` to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
246
+ * - `setDefaultsOnInsert`: `true` by default. Set to `false` to stop Mongoose from applying schema defaults when an update creates a new document with `upsert`.
247
+ * - `strictPopulate`: `true` by default. Set to `false` to allow populating paths that aren't in the schema.
248
+ * - `strictQuery`: `false` by default. May be `false`, `true`, or `'throw'`. Sets the default [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
249
+ * - `strict`: `true` by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
250
+ * - `strictRead`: `false` by default. May be `false`, `true`, or `'throw'`. Sets the default [strictRead](https://mongoosejs.com/docs/guide.html#strictRead) mode for schemas.
251
+ * - `timestamps.createdAt.immutable`: `true` by default. If `false`, it will change the `createdAt` field to be [`immutable: false`](https://mongoosejs.com/docs/api/schematype.html#SchemaType.prototype.immutable()) which means you can update the `createdAt`
252
+ * - `toJSON`: `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](https://mongoosejs.com/docs/api/document.html#Document.prototype.toJSON()), for determining how Mongoose documents get serialized by `JSON.stringify()`
253
+ * - `toObject`: `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject())
254
+ * - `transactionAsyncLocalStorage`: `false` by default. If `true`, Mongoose will automatically pass the `session` to any operation executing within a transaction executor function. See [transaction AsyncLocalStorage documentation](https://mongoosejs.com/docs/transactions.html#asynclocalstorage)
255
+ * - `translateAliases`: `false` by default. If `true`, Mongoose will automatically translate aliases to their original paths before sending the query to MongoDB.
256
+ * - `updatePipeline`: `false` by default. If `true`, allows passing update pipelines (arrays) to update operations by default without explicitly setting `updatePipeline: true` in each query.
257
+ *
258
+ * @param {string|object} key The name of the option or an object of multiple key-value pairs
259
+ * @param {string|Function|boolean} value The value of the option, unused if "key" is an object
260
+ * @returns {Mongoose} The used Mongoose instance
261
+ * @api public
262
+ */
263
+
264
+ Mongoose.prototype.set = function getsetOptions(key, value) {
265
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
266
+
267
+ if (key == null) {
268
+ const error = new SetOptionError();
269
+ error.addError(String(key), new SetOptionError.SetOptionInnerError(String(key)));
270
+ throw error;
271
+ }
272
+
273
+ if (arguments.length === 1 && typeof key !== 'object') {
274
+ if (VALID_OPTIONS.indexOf(key) === -1) {
275
+ const error = new SetOptionError();
276
+ error.addError(key, new SetOptionError.SetOptionInnerError(key));
277
+ throw error;
278
+ }
279
+
280
+ return _mongoose.options[key];
281
+ }
282
+
283
+ let options = {};
284
+
285
+ if (arguments.length === 2) {
286
+ options = { [key]: value };
287
+ }
288
+
289
+ if (arguments.length === 1 && typeof key === 'object') {
290
+ options = key;
291
+ }
292
+
293
+ // array for errors to collect all errors for all key-value pairs, like ".validate"
294
+ let error = undefined;
295
+
296
+ for (const [optionKey, optionValue] of Object.entries(options)) {
297
+ if (VALID_OPTIONS.indexOf(optionKey) === -1) {
298
+ if (!error) {
299
+ error = new SetOptionError();
300
+ }
301
+ error.addError(optionKey, new SetOptionError.SetOptionInnerError(optionKey));
302
+ continue;
303
+ }
304
+
305
+ _mongoose.options[optionKey] = optionValue;
306
+
307
+ if (optionKey === 'objectIdGetter') {
308
+ if (optionValue) {
309
+ Object.defineProperty(_mongoose.Types.ObjectId.prototype, '_id', {
310
+ enumerable: false,
311
+ configurable: true,
312
+ get: function() {
313
+ return this;
314
+ }
315
+ });
316
+ } else {
317
+ delete _mongoose.Types.ObjectId.prototype._id;
318
+ }
319
+ } else if (optionKey === 'transactionAsyncLocalStorage') {
320
+ if (optionValue && !_mongoose.transactionAsyncLocalStorage) {
321
+ _mongoose.transactionAsyncLocalStorage = new AsyncLocalStorage();
322
+ } else if (!optionValue && _mongoose.transactionAsyncLocalStorage) {
323
+ delete _mongoose.transactionAsyncLocalStorage;
324
+ }
325
+ } else if (optionKey === 'createInitialConnection') {
326
+ if (optionValue && !_mongoose.connection) {
327
+ _createDefaultConnection(_mongoose);
328
+ } else if (optionValue === false && _mongoose.connection?.[defaultConnectionSymbol]) {
329
+ if (_mongoose.connection.readyState === STATES.disconnected && utils.hasOwnKeys(_mongoose.connection.models) === false) {
330
+ _mongoose.connections.shift();
331
+ }
332
+ }
333
+ } else if (optionKey === 'returnOriginal') {
334
+ if (_mongoose.options.returnDocument != null) {
335
+ throw new MongooseError(
336
+ 'Cannot set `returnOriginal` when `returnDocument` is already set. Use `returnDocument` instead.'
337
+ );
338
+ }
339
+ const replacement = optionValue === true ? '\'before\'' : '\'after\'';
340
+ utils.warn(
341
+ 'Mongoose: the `returnOriginal` option for `mongoose.set()` is deprecated. ' +
342
+ 'Use `mongoose.set(\'returnDocument\', ' + replacement + ')` instead.'
343
+ );
344
+ } else if (optionKey === 'returnDocument') {
345
+ if (_mongoose.options.returnOriginal != null) {
346
+ throw new MongooseError(
347
+ 'Cannot set `returnDocument` when `returnOriginal` is already set. Use `returnDocument` instead of `returnOriginal`.'
348
+ );
349
+ }
350
+ }
351
+ }
352
+
353
+ if (error) {
354
+ throw error;
355
+ }
356
+
357
+ return _mongoose;
358
+ };
359
+
360
+ /**
361
+ * Gets mongoose options
362
+ *
363
+ * #### Example:
364
+ *
365
+ * mongoose.get('test') // returns the 'test' value
366
+ *
367
+ * @param {string} key
368
+ * @method get
369
+ * @api public
370
+ */
371
+
372
+ Mongoose.prototype.get = Mongoose.prototype.set;
373
+
374
+ /**
375
+ * Creates a Connection instance.
376
+ *
377
+ * Each `connection` instance maps to a single database. This method is helpful when managing multiple db connections.
378
+ *
379
+ *
380
+ * _Options passed take precedence over options included in connection strings._
381
+ *
382
+ * #### Example:
383
+ *
384
+ * // with mongodb:// URI
385
+ * db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database');
386
+ *
387
+ * // and options
388
+ * const opts = { db: { native_parser: true }}
389
+ * db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database', opts);
390
+ *
391
+ * // replica sets
392
+ * db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database');
393
+ *
394
+ * // and options
395
+ * const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
396
+ * db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database', opts);
397
+ *
398
+ * // initialize now, connect later
399
+ * db = mongoose.createConnection();
400
+ * await db.openUri('mongodb://127.0.0.1:27017/database');
401
+ *
402
+ * @param {string} uri mongodb URI to connect to
403
+ * @param {object} [options] passed down to the [MongoDB driver's `connect()` function](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/MongoClientOptions.html), except for 4 mongoose-specific options explained below.
404
+ * @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.
405
+ * @param {string} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string.
406
+ * @param {string} [options.user] username for authentication, equivalent to `options.auth.username`. Maintained for backwards compatibility.
407
+ * @param {string} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
408
+ * @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
409
+ * @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).
410
+ * @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).
411
+ * @param {number} [options.socketTimeoutMS=0] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. Defaults to 0, which means Node.js will not time out the socket due to inactivity. A socket may be inactive because of either no activity or a long-running operation. 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.
412
+ * @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.
413
+ * @return {Connection} the created Connection object. Connections are not thenable, so you can't do `await mongoose.createConnection()`. To await use `mongoose.createConnection(uri).asPromise()` instead.
414
+ * @api public
415
+ */
416
+
417
+ Mongoose.prototype.createConnection = function createConnection(uri, options) {
418
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
419
+
420
+ const Connection = _mongoose.__driver.Connection;
421
+ const conn = new Connection(_mongoose);
422
+ _mongoose.connections.push(conn);
423
+ _mongoose.nextConnectionId++;
424
+ _mongoose.events.emit('createConnection', conn);
425
+
426
+ if (arguments.length > 0) {
427
+ conn.openUri(uri, { ...options, _fireAndForget: true });
428
+ }
429
+
430
+ return conn;
431
+ };
432
+
433
+ /**
434
+ * Opens the default mongoose connection.
435
+ *
436
+ * #### Example:
437
+ *
438
+ * mongoose.connect('mongodb://user:pass@127.0.0.1:port/database');
439
+ *
440
+ * // replica sets
441
+ * const uri = 'mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/mydatabase';
442
+ * mongoose.connect(uri);
443
+ *
444
+ * // with options
445
+ * mongoose.connect(uri, options);
446
+ *
447
+ * // Using `await` throws "MongooseServerSelectionError: Server selection timed out after 30000 ms"
448
+ * // if Mongoose can't connect.
449
+ * const uri = 'mongodb://nonexistent.domain:27000';
450
+ * await mongoose.connect(uri);
451
+ *
452
+ * @param {string} uri mongodb URI to connect to
453
+ * @param {object} [options] passed down to the [MongoDB driver's `connect()` function](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/MongoClientOptions.html), except for 4 mongoose-specific options explained below.
454
+ * @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.
455
+ * @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.
456
+ * @param {string} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
457
+ * @param {string} [options.user] username for authentication, equivalent to `options.auth.username`. Maintained for backwards compatibility.
458
+ * @param {string} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
459
+ * @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).
460
+ * @param {number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection.
461
+ * @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).
462
+ * @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.
463
+ * @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
464
+ * @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.
465
+ * @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.
466
+ * @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.
467
+ * @see Mongoose#createConnection https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.createConnection()
468
+ * @api public
469
+ * @return {Promise} resolves to `this` if connection succeeded
470
+ */
471
+
472
+ Mongoose.prototype.connect = async function connect(uri, options) {
473
+ if (typeof options === 'function' || (arguments.length >= 3 && typeof arguments[2] === 'function')) {
474
+ throw new MongooseError('Mongoose.prototype.connect() no longer accepts a callback');
475
+ }
476
+
477
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
478
+ if (_mongoose.connection == null) {
479
+ _createDefaultConnection(_mongoose);
480
+ }
481
+ const conn = _mongoose.connection;
482
+
483
+ return conn.openUri(uri, options).then(() => _mongoose);
484
+ };
485
+
486
+ /**
487
+ * Runs `.close()` on all connections in parallel.
488
+ *
489
+ * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred.
490
+ * @api public
491
+ */
492
+
493
+ Mongoose.prototype.disconnect = async function disconnect() {
494
+ if (arguments.length >= 1 && typeof arguments[0] === 'function') {
495
+ throw new MongooseError('Mongoose.prototype.disconnect() no longer accepts a callback');
496
+ }
497
+
498
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
499
+
500
+ const remaining = _mongoose.connections.length;
501
+ if (remaining <= 0) {
502
+ return;
503
+ }
504
+ await Promise.all(_mongoose.connections.map(conn => conn.close()));
505
+ };
506
+
507
+ /**
508
+ * Starts a [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
509
+ * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
510
+ * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
511
+ *
512
+ * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`.
513
+ * Sessions are scoped to a connection, so calling `mongoose.startSession()`
514
+ * starts a session on the [default mongoose connection](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.connection).
515
+ *
516
+ * @param {object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/7.0/classes/MongoClient.html#startSession)
517
+ * @param {boolean} [options.causalConsistency=true] set to false to disable causal consistency
518
+ * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
519
+ * @api public
520
+ */
521
+
522
+ Mongoose.prototype.startSession = function startSession() {
523
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
524
+
525
+ return _mongoose.connection.startSession.apply(_mongoose.connection, arguments);
526
+ };
527
+
528
+ /**
529
+ * Getter/setter around function for pluralizing collection names.
530
+ *
531
+ * @param {Function|null} [fn] overwrites the function used to pluralize collection names
532
+ * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`.
533
+ * @api public
534
+ */
535
+
536
+ Mongoose.prototype.pluralize = function pluralize(fn) {
537
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
538
+
539
+ if (arguments.length > 0) {
540
+ _mongoose._pluralize = fn;
541
+ }
542
+ return _mongoose._pluralize;
543
+ };
544
+
545
+ /**
546
+ * Defines a model or retrieves it.
547
+ *
548
+ * Models defined on the `mongoose` instance are available to all connection
549
+ * created by the same `mongoose` instance.
550
+ *
551
+ * If you call `mongoose.model()` with twice the same name but a different schema,
552
+ * you will get an `OverwriteModelError`. If you call `mongoose.model()` with
553
+ * the same name and same schema, you'll get the same schema back.
554
+ *
555
+ * #### Example:
556
+ *
557
+ * const mongoose = require('mongoose');
558
+ *
559
+ * // define an Actor model with this mongoose instance
560
+ * const schema = new Schema({ name: String });
561
+ * mongoose.model('Actor', schema);
562
+ *
563
+ * // create a new connection
564
+ * const conn = mongoose.createConnection(..);
565
+ *
566
+ * // create Actor model
567
+ * const Actor = conn.model('Actor', schema);
568
+ * conn.model('Actor') === Actor; // true
569
+ * conn.model('Actor', schema) === Actor; // true, same schema
570
+ * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
571
+ *
572
+ * // This throws an `OverwriteModelError` because the schema is different.
573
+ * conn.model('Actor', new Schema({ name: String }));
574
+ *
575
+ * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._
576
+ *
577
+ * #### Example:
578
+ *
579
+ * const schema = new Schema({ name: String }, { collection: 'actor' });
580
+ *
581
+ * // or
582
+ *
583
+ * schema.set('collection', 'actor');
584
+ *
585
+ * // or
586
+ *
587
+ * const collectionName = 'actor';
588
+ * const M = mongoose.model('Actor', schema, collectionName);
589
+ *
590
+ * @param {string|Function} name model name or class extending Model
591
+ * @param {Schema} [schema] the schema to use.
592
+ * @param {string} [collection] name (optional, inferred from model name)
593
+ * @param {object} [options]
594
+ * @param {boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError`
595
+ * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist.
596
+ * @api public
597
+ */
598
+
599
+ Mongoose.prototype.model = function model(name, schema, collection, options) {
600
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
601
+
602
+ if (typeof schema === 'string') {
603
+ collection = schema;
604
+ schema = false;
605
+ }
606
+
607
+ if (arguments.length === 1) {
608
+ const model = getOwnProperty(_mongoose.models, name);
609
+ if (!model) {
610
+ throw new _mongoose.Error.MissingSchemaError(name);
611
+ }
612
+ return model;
613
+ }
614
+
615
+ if (utils.isObject(schema) && !(schema instanceof Schema)) {
616
+ schema = new Schema(schema);
617
+ }
618
+ if (schema && !(schema instanceof Schema)) {
619
+ throw new _mongoose.Error('The 2nd parameter to `mongoose.model()` should be a ' +
620
+ 'schema or a POJO');
621
+ }
622
+
623
+ // handle internal options from connection.model()
624
+ options = options || {};
625
+
626
+ const originalSchema = schema;
627
+ if (schema) {
628
+ if (_mongoose.get('cloneSchemas')) {
629
+ schema = schema.clone();
630
+ }
631
+ _mongoose._applyPlugins(schema);
632
+ }
633
+
634
+ // connection.model() may be passing a different schema for
635
+ // an existing model name. in this case don't read from cache.
636
+ const overwriteModels = Object.hasOwn(_mongoose.options, 'overwriteModels') ?
637
+ _mongoose.options.overwriteModels :
638
+ options.overwriteModels;
639
+ if (Object.hasOwn(_mongoose.models, name) && options.cache !== false && overwriteModels !== true) {
640
+ if (originalSchema?.instanceOfSchema &&
641
+ originalSchema !== _mongoose.models[name].schema) {
642
+ throw new _mongoose.Error.OverwriteModelError(name);
643
+ }
644
+ if (collection && collection !== _mongoose.models[name].collection.name) {
645
+ // subclass current model with alternate collection
646
+ const model = _mongoose.models[name];
647
+ schema = model.prototype.schema;
648
+ const sub = model.__subclass(_mongoose.connection, schema, collection);
649
+ // do not cache the sub model
650
+ return sub;
651
+ }
652
+ return _mongoose.models[name];
653
+ }
654
+ if (schema == null) {
655
+ throw new _mongoose.Error.MissingSchemaError(name);
656
+ }
657
+
658
+ const model = _mongoose._model(name, schema, collection, options);
659
+ _mongoose.connection.models[name] = model;
660
+ _mongoose.models[name] = model;
661
+
662
+ return model;
663
+ };
664
+
665
+ /*!
666
+ * ignore
667
+ */
668
+
669
+ Mongoose.prototype._model = function _model(name, schema, collection, options) {
670
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
671
+
672
+ let model;
673
+ if (typeof name === 'function') {
674
+ model = name;
675
+ name = model.name;
676
+ if (!(model.prototype instanceof Model)) {
677
+ throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
678
+ }
679
+ }
680
+ // Models are stored in POJOs keyed by name, so `__proto__` would change their prototype
681
+ if (name === '__proto__') {
682
+ throw new _mongoose.Error('Model name "__proto__" is not allowed');
683
+ }
684
+
685
+ if (schema) {
686
+ if (_mongoose.get('cloneSchemas')) {
687
+ schema = schema.clone();
688
+ }
689
+ _mongoose._applyPlugins(schema);
690
+ }
691
+
692
+ // Apply relevant "global" options to the schema
693
+ if (schema == null || !('pluralization' in schema.options)) {
694
+ schema.options.pluralization = _mongoose.options.pluralization;
695
+ }
696
+
697
+ if (!collection) {
698
+ collection = schema.get('collection') ||
699
+ utils.toCollectionName(name, _mongoose.pluralize());
700
+ }
701
+
702
+ applyEmbeddedDiscriminators(schema);
703
+
704
+ const connection = options.connection || _mongoose.connection;
705
+ model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose);
706
+ // Errors handled internally, so safe to ignore error
707
+ model.init().catch(function $modelInitNoop() {});
708
+
709
+ connection.emit('model', model);
710
+
711
+ if (schema._applyDiscriminators != null) {
712
+ for (const disc of schema._applyDiscriminators.keys()) {
713
+ const {
714
+ schema: discriminatorSchema,
715
+ options
716
+ } = schema._applyDiscriminators.get(disc);
717
+ model.discriminator(disc, discriminatorSchema, options);
718
+ }
719
+ }
720
+
721
+ return model;
722
+ };
723
+
724
+ /**
725
+ * Removes the model named `name` from the default connection, if it exists.
726
+ * You can use this function to clean up any models you created in your tests to
727
+ * prevent OverwriteModelErrors.
728
+ *
729
+ * Equivalent to `mongoose.connection.deleteModel(name)`.
730
+ *
731
+ * #### Example:
732
+ *
733
+ * mongoose.model('User', new Schema({ name: String }));
734
+ * console.log(mongoose.model('User')); // Model object
735
+ * mongoose.deleteModel('User');
736
+ * console.log(mongoose.model('User')); // undefined
737
+ *
738
+ * // Usually useful in a Mocha `afterEach()` hook
739
+ * afterEach(function() {
740
+ * mongoose.deleteModel(/.+/); // Delete every model
741
+ * });
742
+ *
743
+ * @api public
744
+ * @param {string|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
745
+ * @return {Mongoose} this
746
+ */
747
+
748
+ Mongoose.prototype.deleteModel = function deleteModel(name) {
749
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
750
+
751
+ _mongoose.connection.deleteModel(name);
752
+ delete _mongoose.models[name];
753
+ return _mongoose;
754
+ };
755
+
756
+ /**
757
+ * Returns an array of model names created on this instance of Mongoose.
758
+ *
759
+ * #### Note:
760
+ *
761
+ * _Does not include names of models created using `connection.model()`._
762
+ *
763
+ * @api public
764
+ * @return {Array}
765
+ */
766
+
767
+ Mongoose.prototype.modelNames = function modelNames() {
768
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
769
+
770
+ const names = Object.keys(_mongoose.models);
771
+ return names;
772
+ };
773
+
774
+ /**
775
+ * Applies global plugins to `schema`.
776
+ *
777
+ * @param {Schema} schema
778
+ * @api private
779
+ */
780
+
781
+ Mongoose.prototype._applyPlugins = function _applyPlugins(schema, options) {
782
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
783
+
784
+ options = options || {};
785
+ options.applyPluginsToDiscriminators = _mongoose.options?.applyPluginsToDiscriminators || false;
786
+ options.applyPluginsToChildSchemas = typeof _mongoose.options?.applyPluginsToChildSchemas === 'boolean' ?
787
+ _mongoose.options.applyPluginsToChildSchemas :
788
+ true;
789
+ applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
790
+ };
791
+
792
+ /**
793
+ * Declares a global plugin executed on all Schemas.
794
+ *
795
+ * Equivalent to calling `.plugin(fn)` on each Schema you create.
796
+ *
797
+ * @param {Function} fn plugin callback
798
+ * @param {object} [opts] optional options
799
+ * @return {Mongoose} this
800
+ * @see plugins https://mongoosejs.com/docs/plugins.html
801
+ * @api public
802
+ */
803
+
804
+ Mongoose.prototype.plugin = function plugin(fn, opts) {
805
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
806
+
807
+ _mongoose.plugins.push([fn, opts]);
808
+ return _mongoose;
809
+ };
810
+
811
+ /**
812
+ * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.connections).
813
+ *
814
+ * #### Example:
815
+ *
816
+ * const mongoose = require('mongoose');
817
+ * mongoose.connect(...);
818
+ * mongoose.connection.on('error', cb);
819
+ *
820
+ * This is the connection used by default for every model created using [mongoose.model](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.model()).
821
+ *
822
+ * To create a new connection, use [`createConnection()`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.createConnection()).
823
+ *
824
+ * @memberOf Mongoose
825
+ * @instance
826
+ * @property {Connection} connection
827
+ * @api public
828
+ */
829
+
830
+ Mongoose.prototype.__defineGetter__('connection', function() {
831
+ return this.connections[0];
832
+ });
833
+
834
+ Mongoose.prototype.__defineSetter__('connection', function(v) {
835
+ if (v instanceof this.__driver.Connection) {
836
+ this.connections[0] = v;
837
+ this.models = v.models;
838
+ }
839
+ });
840
+
841
+ /**
842
+ * An array containing all [connections](connection.html) associated with this
843
+ * Mongoose instance. By default, there is 1 connection. Calling
844
+ * [`createConnection()`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.createConnection()) adds a connection
845
+ * to this array.
846
+ *
847
+ * #### Example:
848
+ *
849
+ * const mongoose = require('mongoose');
850
+ * mongoose.connections.length; // 1, just the default connection
851
+ * mongoose.connections[0] === mongoose.connection; // true
852
+ *
853
+ * mongoose.createConnection('mongodb://127.0.0.1:27017/test');
854
+ * mongoose.connections.length; // 2
855
+ *
856
+ * @memberOf Mongoose
857
+ * @instance
858
+ * @property {Array} connections
859
+ * @api public
860
+ */
861
+
862
+ Mongoose.prototype.connections;
863
+
864
+ /**
865
+ * An integer containing the value of the next connection id. Calling
866
+ * [`createConnection()`](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.createConnection()) increments
867
+ * this value.
868
+ *
869
+ * #### Example:
870
+ *
871
+ * const mongoose = require('mongoose');
872
+ * mongoose.createConnection(); // id `0`, `nextConnectionId` becomes `1`
873
+ * mongoose.createConnection(); // id `1`, `nextConnectionId` becomes `2`
874
+ * mongoose.connections[0].destroy() // Removes connection with id `0`
875
+ * mongoose.createConnection(); // id `2`, `nextConnectionId` becomes `3`
876
+ *
877
+ * @memberOf Mongoose
878
+ * @instance
879
+ * @property {number} nextConnectionId
880
+ * @api private
881
+ */
882
+
883
+ Mongoose.prototype.nextConnectionId;
884
+
885
+ /**
886
+ * The Mongoose Aggregate constructor
887
+ *
888
+ * @method Aggregate
889
+ * @api public
890
+ */
891
+
892
+ Mongoose.prototype.Aggregate = Aggregate;
893
+
894
+ /**
895
+ * The Base Mongoose Collection class. `mongoose.Collection` extends from this class.
896
+ *
897
+ * @memberOf Mongoose
898
+ * @instance
899
+ * @method Collection
900
+ * @api public
901
+ */
902
+
903
+ Mongoose.prototype.BaseCollection = require('./collection');
904
+
905
+ /**
906
+ * The Mongoose Collection constructor
907
+ *
908
+ * @memberOf Mongoose
909
+ * @instance
910
+ * @method Collection
911
+ * @api public
912
+ */
913
+
914
+ Object.defineProperty(Mongoose.prototype, 'Collection', {
915
+ get: function() {
916
+ return this.__driver.Collection;
917
+ },
918
+ set: function(Collection) {
919
+ this.__driver.Collection = Collection;
920
+ }
921
+ });
922
+
923
+ /**
924
+ * The Mongoose [Connection](https://mongoosejs.com/docs/api/connection.html#Connection()) constructor
925
+ *
926
+ * @memberOf Mongoose
927
+ * @instance
928
+ * @method Connection
929
+ * @api public
930
+ */
931
+
932
+ Object.defineProperty(Mongoose.prototype, 'Connection', {
933
+ get: function() {
934
+ return this.__driver.Connection;
935
+ },
936
+ set: function(Connection) {
937
+ if (Connection === this.__driver.Connection) {
938
+ return;
939
+ }
940
+
941
+ this.__driver.Connection = Connection;
942
+ }
943
+ });
944
+
945
+ /**
946
+ * The Base Mongoose Connection class. `mongoose.Connection` extends from this class.
947
+ *
948
+ * @memberOf Mongoose
949
+ * @instance
950
+ * @method Connection
951
+ * @api public
952
+ */
953
+
954
+ Mongoose.prototype.BaseConnection = require('./connection');
955
+
956
+ /**
957
+ * The Mongoose version
958
+ *
959
+ * #### Example:
960
+ *
961
+ * console.log(mongoose.version); // '5.x.x'
962
+ *
963
+ * @property version
964
+ * @api public
965
+ */
966
+
967
+ Mongoose.prototype.version = pkg.version;
968
+
969
+ /**
970
+ * The Mongoose constructor
971
+ *
972
+ * The exports of the mongoose module is an instance of this class.
973
+ *
974
+ * #### Example:
975
+ *
976
+ * const mongoose = require('mongoose');
977
+ * const mongoose2 = new mongoose.Mongoose();
978
+ *
979
+ * @method Mongoose
980
+ * @api public
981
+ */
982
+
983
+ Mongoose.prototype.Mongoose = Mongoose;
984
+
985
+ /**
986
+ * The Mongoose [Schema](https://mongoosejs.com/docs/api/schema.html#Schema()) constructor
987
+ *
988
+ * #### Example:
989
+ *
990
+ * const mongoose = require('mongoose');
991
+ * const Schema = mongoose.Schema;
992
+ * const CatSchema = new Schema(..);
993
+ *
994
+ * @method Schema
995
+ * @api public
996
+ */
997
+
998
+ Mongoose.prototype.Schema = Schema;
999
+
1000
+ /**
1001
+ * The Mongoose [SchemaType](https://mongoosejs.com/docs/api/schematype.html#SchemaType()) constructor
1002
+ *
1003
+ * @method SchemaType
1004
+ * @api public
1005
+ */
1006
+
1007
+ Mongoose.prototype.SchemaType = SchemaType;
1008
+
1009
+ /**
1010
+ * The various Mongoose SchemaTypes.
1011
+ *
1012
+ * #### Note:
1013
+ *
1014
+ * _Alias of mongoose.Schema.Types for backwards compatibility._
1015
+ *
1016
+ * @property SchemaTypes
1017
+ * @see Schema.SchemaTypes https://mongoosejs.com/docs/schematypes.html
1018
+ * @api public
1019
+ */
1020
+
1021
+ Mongoose.prototype.SchemaTypes = Schema.Types;
1022
+
1023
+ /**
1024
+ * The Mongoose [VirtualType](https://mongoosejs.com/docs/api/virtualtype.html#VirtualType()) constructor
1025
+ *
1026
+ * @method VirtualType
1027
+ * @api public
1028
+ */
1029
+
1030
+ Mongoose.prototype.VirtualType = VirtualType;
1031
+
1032
+ /**
1033
+ * The various Mongoose Types.
1034
+ *
1035
+ * #### Example:
1036
+ *
1037
+ * const mongoose = require('mongoose');
1038
+ * const array = mongoose.Types.Array;
1039
+ *
1040
+ * #### Types:
1041
+ *
1042
+ * - [Array](https://mongoosejs.com/docs/schematypes.html#arrays)
1043
+ * - [Buffer](https://mongoosejs.com/docs/schematypes.html#buffers)
1044
+ * - [Embedded](https://mongoosejs.com/docs/schematypes.html#schemas)
1045
+ * - [DocumentArray](https://mongoosejs.com/docs/api/documentarray.html)
1046
+ * - [Decimal128](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.Decimal128)
1047
+ * - [ObjectId](https://mongoosejs.com/docs/schematypes.html#objectids)
1048
+ * - [Map](https://mongoosejs.com/docs/schematypes.html#maps)
1049
+ * - [Subdocument](https://mongoosejs.com/docs/schematypes.html#schemas)
1050
+ * - [Int32](https://mongoosejs.com/docs/schematypes.html#int32)
1051
+ *
1052
+ * Using this exposed access to the `ObjectId` type, we can construct ids on demand.
1053
+ *
1054
+ * const ObjectId = mongoose.Types.ObjectId;
1055
+ * const id1 = new ObjectId;
1056
+ *
1057
+ * @property Types
1058
+ * @api public
1059
+ */
1060
+
1061
+ Mongoose.prototype.Types = Types;
1062
+
1063
+ /**
1064
+ * The Mongoose [Query](https://mongoosejs.com/docs/api/query.html#Query()) constructor.
1065
+ *
1066
+ * @method Query
1067
+ * @api public
1068
+ */
1069
+
1070
+ Mongoose.prototype.Query = Query;
1071
+
1072
+ /**
1073
+ * The Mongoose [Model](https://mongoosejs.com/docs/api/model.html#Model()) constructor.
1074
+ *
1075
+ * @method Model
1076
+ * @api public
1077
+ */
1078
+
1079
+ Mongoose.prototype.Model = Model;
1080
+
1081
+ /**
1082
+ * The Mongoose [Document](https://mongoosejs.com/docs/api/document.html) constructor.
1083
+ *
1084
+ * @method Document
1085
+ * @api public
1086
+ */
1087
+
1088
+ Mongoose.prototype.Document = Document;
1089
+
1090
+ /**
1091
+ * The Mongoose ObjectId [SchemaType](https://mongoosejs.com/docs/schematypes.html). Used for
1092
+ * declaring paths in your schema that should be
1093
+ * [MongoDB ObjectIds](https://www.mongodb.com/docs/manual/reference/method/ObjectId/).
1094
+ * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
1095
+ * instead.
1096
+ *
1097
+ * #### Example:
1098
+ *
1099
+ * const childSchema = new Schema({ parentId: mongoose.ObjectId });
1100
+ *
1101
+ * @property ObjectId
1102
+ * @api public
1103
+ */
1104
+
1105
+ Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
1106
+
1107
+ /**
1108
+ * Returns true if Mongoose can cast the given value to an ObjectId, or
1109
+ * false otherwise.
1110
+ *
1111
+ * #### Example:
1112
+ *
1113
+ * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
1114
+ * mongoose.isValidObjectId('0123456789ab'); // true
1115
+ * mongoose.isValidObjectId(6); // true
1116
+ * mongoose.isValidObjectId(new User({ name: 'test' })); // true
1117
+ *
1118
+ * mongoose.isValidObjectId({ test: 42 }); // false
1119
+ *
1120
+ * @method isValidObjectId
1121
+ * @param {any} v
1122
+ * @returns {boolean} true if `v` is something Mongoose can coerce to an ObjectId
1123
+ * @api public
1124
+ */
1125
+
1126
+ Mongoose.prototype.isValidObjectId = function isValidObjectId(v) {
1127
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
1128
+ return _mongoose.Types.ObjectId.isValid(v);
1129
+ };
1130
+
1131
+ /**
1132
+ * Returns true if the given value is a Mongoose ObjectId (using `instanceof`) or if the
1133
+ * given value is a 24 character hex string, which is the most commonly used string representation
1134
+ * of an ObjectId.
1135
+ *
1136
+ * This function is similar to `isValidObjectId()`, but considerably more strict, because
1137
+ * `isValidObjectId()` will return `true` for _any_ value that Mongoose can convert to an
1138
+ * ObjectId. That includes Mongoose documents, any string of length 12, and any number.
1139
+ * `isObjectIdOrHexString()` returns true only for `ObjectId` instances or 24 character hex
1140
+ * strings, and will return false for numbers, documents, and strings of length 12.
1141
+ *
1142
+ * #### Example:
1143
+ *
1144
+ * mongoose.isObjectIdOrHexString(new mongoose.Types.ObjectId()); // true
1145
+ * mongoose.isObjectIdOrHexString('62261a65d66c6be0a63c051f'); // true
1146
+ *
1147
+ * mongoose.isObjectIdOrHexString('0123456789ab'); // false
1148
+ * mongoose.isObjectIdOrHexString(6); // false
1149
+ * mongoose.isObjectIdOrHexString(new User({ name: 'test' })); // false
1150
+ * mongoose.isObjectIdOrHexString({ test: 42 }); // false
1151
+ *
1152
+ * @method isObjectIdOrHexString
1153
+ * @param {any} v
1154
+ * @returns {boolean} true if `v` is an ObjectId instance _or_ a 24 char hex string
1155
+ * @api public
1156
+ */
1157
+
1158
+ Mongoose.prototype.isObjectIdOrHexString = function isObjectIdOrHexString(v) {
1159
+ return isBsonType(v, 'ObjectId') || (typeof v === 'string' && objectIdHexRegexp.test(v));
1160
+ };
1161
+
1162
+ /**
1163
+ *
1164
+ * Syncs all the indexes for the models registered with this connection.
1165
+ *
1166
+ * @param {object} options
1167
+ * @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.
1168
+ * @return {Promise} Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.
1169
+ */
1170
+ Mongoose.prototype.syncIndexes = function syncIndexes(options) {
1171
+ const _mongoose = this instanceof Mongoose ? this : mongoose;
1172
+ return _mongoose.connection.syncIndexes(options);
1173
+ };
1174
+
1175
+ /**
1176
+ * The Mongoose Decimal128 [SchemaType](https://mongoosejs.com/docs/schematypes.html). Used for
1177
+ * declaring paths in your schema that should be
1178
+ * [128-bit decimal floating points](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
1179
+ * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
1180
+ * instead.
1181
+ *
1182
+ * #### Example:
1183
+ *
1184
+ * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });
1185
+ *
1186
+ * @property Decimal128
1187
+ * @api public
1188
+ */
1189
+
1190
+ Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128;
1191
+
1192
+
1193
+ /**
1194
+ * The Mongoose Mixed [SchemaType](https://mongoosejs.com/docs/schematypes.html). Used for
1195
+ * declaring paths in your schema that Mongoose's change tracking, casting,
1196
+ * and validation should ignore.
1197
+ *
1198
+ * #### Example:
1199
+ *
1200
+ * const schema = new Schema({ arbitrary: mongoose.Mixed });
1201
+ *
1202
+ * @property Mixed
1203
+ * @api public
1204
+ */
1205
+
1206
+ Mongoose.prototype.Mixed = SchemaTypes.Mixed;
1207
+
1208
+ /**
1209
+ * The Mongoose Date [SchemaType](https://mongoosejs.com/docs/schematypes.html).
1210
+ *
1211
+ * #### Example:
1212
+ *
1213
+ * const schema = new Schema({ test: Date });
1214
+ * schema.path('test') instanceof mongoose.Date; // true
1215
+ *
1216
+ * @property Date
1217
+ * @api public
1218
+ */
1219
+
1220
+ Mongoose.prototype.Date = SchemaTypes.Date;
1221
+
1222
+ /**
1223
+ * The Mongoose Number [SchemaType](https://mongoosejs.com/docs/schematypes.html). Used for
1224
+ * declaring paths in your schema that Mongoose should cast to numbers.
1225
+ *
1226
+ * #### Example:
1227
+ *
1228
+ * const schema = new Schema({ num: mongoose.Number });
1229
+ * // Equivalent to:
1230
+ * const schema = new Schema({ num: 'number' });
1231
+ *
1232
+ * @property Number
1233
+ * @api public
1234
+ */
1235
+
1236
+ Mongoose.prototype.Number = SchemaTypes.Number;
1237
+
1238
+ /**
1239
+ * The [MongooseError](https://mongoosejs.com/docs/api/error.html#Error()) constructor.
1240
+ *
1241
+ * @method Error
1242
+ * @api public
1243
+ */
1244
+
1245
+ Mongoose.prototype.Error = MongooseError;
1246
+ Mongoose.prototype.MongooseError = MongooseError;
1247
+
1248
+ /**
1249
+ * Mongoose uses this function to get the current time when setting
1250
+ * [timestamps](https://mongoosejs.com/docs/guide.html#timestamps). You may stub out this function
1251
+ * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
1252
+ *
1253
+ * @method now
1254
+ * @returns {Date} the current time
1255
+ * @api public
1256
+ */
1257
+
1258
+ Mongoose.prototype.now = function now() { return new Date(); };
1259
+
1260
+ /**
1261
+ * The Mongoose CastError constructor
1262
+ *
1263
+ * @method CastError
1264
+ * @param {string} type The name of the type
1265
+ * @param {any} value The value that failed to cast
1266
+ * @param {string} path The path `a.b.c` in the doc where this cast error occurred
1267
+ * @param {Error} [reason] The original error that was thrown
1268
+ * @api public
1269
+ */
1270
+
1271
+ Mongoose.prototype.CastError = MongooseError.CastError;
1272
+
1273
+ /**
1274
+ * The constructor used for schematype options
1275
+ *
1276
+ * @method SchemaTypeOptions
1277
+ * @api public
1278
+ */
1279
+
1280
+ Mongoose.prototype.SchemaTypeOptions = require('./options/schemaTypeOptions');
1281
+
1282
+ /**
1283
+ * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
1284
+ *
1285
+ * @property mongo
1286
+ * @api public
1287
+ */
1288
+
1289
+ Mongoose.prototype.mongo = null;
1290
+
1291
+ /**
1292
+ * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
1293
+ *
1294
+ * @property mquery
1295
+ * @api public
1296
+ */
1297
+
1298
+ Mongoose.prototype.mquery = require('mquery');
1299
+
1300
+ /**
1301
+ * Sanitizes query filters against [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html)
1302
+ * by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`.
1303
+ *
1304
+ * ```javascript
1305
+ * const obj = { username: 'val', pwd: { $ne: null } };
1306
+ * sanitizeFilter(obj);
1307
+ * obj; // { username: 'val', pwd: { $eq: { $ne: null } } });
1308
+ * ```
1309
+ *
1310
+ * @method sanitizeFilter
1311
+ * @param {object} filter
1312
+ * @returns {object} the sanitized object
1313
+ * @api public
1314
+ */
1315
+
1316
+ Mongoose.prototype.sanitizeFilter = sanitizeFilter;
1317
+
1318
+ /**
1319
+ * Tells `sanitizeFilter()` to skip the given object when filtering out potential [query selector injection attacks](https://thecodebarbarian.com/2014/09/04/defending-against-query-selector-injection-attacks.html).
1320
+ * Use this method when you have a known query selector that you want to use.
1321
+ *
1322
+ * ```javascript
1323
+ * const obj = { username: 'val', pwd: trusted({ $type: 'string', $eq: 'my secret' }) };
1324
+ * sanitizeFilter(obj);
1325
+ *
1326
+ * // Note that `sanitizeFilter()` did not add `$eq` around `$type`.
1327
+ * obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } });
1328
+ * ```
1329
+ *
1330
+ * @method trusted
1331
+ * @param {object} obj
1332
+ * @returns {object} the passed in object
1333
+ * @api public
1334
+ */
1335
+
1336
+ Mongoose.prototype.trusted = trusted;
1337
+
1338
+ /**
1339
+ * Use this function in `pre()` middleware to skip calling the wrapped function.
1340
+ *
1341
+ * #### Example:
1342
+ *
1343
+ * schema.pre('save', function() {
1344
+ * // Will skip executing `save()`, but will execute post hooks as if
1345
+ * // `save()` had executed with the result `{ matchedCount: 0 }`
1346
+ * return mongoose.skipMiddlewareFunction({ matchedCount: 0 });
1347
+ * });
1348
+ *
1349
+ * @method skipMiddlewareFunction
1350
+ * @param {any} result
1351
+ * @api public
1352
+ */
1353
+
1354
+ Mongoose.prototype.skipMiddlewareFunction = Kareem.skipWrappedFunction;
1355
+
1356
+ /**
1357
+ * Use this function in `post()` middleware to replace the result
1358
+ *
1359
+ * #### Example:
1360
+ *
1361
+ * schema.post('find', function(res) {
1362
+ * // Normally you have to modify `res` in place. But with
1363
+ * // `overwriteMiddlewarResult()`, you can make `find()` return a
1364
+ * // completely different value.
1365
+ * return mongoose.overwriteMiddlewareResult(res.filter(doc => !doc.isDeleted));
1366
+ * });
1367
+ *
1368
+ * @method overwriteMiddlewareResult
1369
+ * @param {any} result
1370
+ * @api public
1371
+ */
1372
+
1373
+ Mongoose.prototype.overwriteMiddlewareResult = Kareem.overwriteResult;
1374
+
1375
+ /**
1376
+ * Use this function in `pre()` middleware to replace the arguments passed to the next middleware or hook.
1377
+ *
1378
+ * #### Example:
1379
+ *
1380
+ * // Suppose you have a schema for time in "HH:MM" string format, but you want to store it as an object { hours, minutes }
1381
+ * const timeStringToObject = (time) => {
1382
+ * if (typeof time !== 'string') return time;
1383
+ * const [hours, minutes] = time.split(':');
1384
+ * return { hours: parseInt(hours), minutes: parseInt(minutes) };
1385
+ * };
1386
+ *
1387
+ * const timeSchema = new Schema({
1388
+ * hours: { type: Number, required: true },
1389
+ * minutes: { type: Number, required: true },
1390
+ * });
1391
+ *
1392
+ * // In a pre('init') hook, replace raw string doc with custom object form
1393
+ * timeSchema.pre('init', function(doc) {
1394
+ * if (typeof doc === 'string') {
1395
+ * return mongoose.overwriteMiddlewareArguments(timeStringToObject(doc));
1396
+ * }
1397
+ * });
1398
+ *
1399
+ * // Now, initializing with a time string gets auto-converted by the hook
1400
+ * const userSchema = new Schema({ time: timeSchema });
1401
+ * const User = mongoose.model('User', userSchema);
1402
+ * const doc = new User({});
1403
+ * doc.$init({ time: '12:30' });
1404
+ *
1405
+ * @method overwriteMiddlewareArguments
1406
+ * @param {...any} args The new arguments to be passed to the next middleware. Pass multiple arguments as a spread, **not** as an array.
1407
+ * @api public
1408
+ */
1409
+
1410
+ Mongoose.prototype.overwriteMiddlewareArguments = Kareem.overwriteArguments;
1411
+
1412
+ /**
1413
+ * Takes in an object and deletes any keys from the object whose values
1414
+ * are strictly equal to `undefined`.
1415
+ * This function is useful for query filters because Mongoose treats
1416
+ * `TestModel.find({ name: undefined })` as `TestModel.find({ name: null })`.
1417
+ *
1418
+ * #### Example:
1419
+ *
1420
+ * const filter = { name: 'John', age: undefined, status: 'active' };
1421
+ * mongoose.omitUndefined(filter); // { name: 'John', status: 'active' }
1422
+ * filter; // { name: 'John', status: 'active' }
1423
+ *
1424
+ * await UserModel.findOne(mongoose.omitUndefined(filter));
1425
+ *
1426
+ * @method omitUndefined
1427
+ * @param {object} [val] the object to remove undefined keys from
1428
+ * @returns {object} the object passed in
1429
+ * @api public
1430
+ */
1431
+
1432
+ Mongoose.prototype.omitUndefined = require('./helpers/omitUndefined');
1433
+
1434
+ /*!
1435
+ * Create a new default connection (`mongoose.connection`) for a Mongoose instance.
1436
+ * No-op if there is already a default connection.
1437
+ */
1438
+
1439
+ function _createDefaultConnection(mongoose) {
1440
+ if (mongoose.connection) {
1441
+ return;
1442
+ }
1443
+ const conn = mongoose.createConnection(); // default connection
1444
+ conn[defaultConnectionSymbol] = true;
1445
+ conn.models = mongoose.models;
1446
+ }
1447
+
1448
+ /**
1449
+ * The exports object is an instance of Mongoose.
1450
+ *
1451
+ * @api private
1452
+ */
1453
+
1454
+ const mongoose = module.exports = exports = new Mongoose({
1455
+ [defaultMongooseSymbol]: true
1456
+ });