@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
@@ -5,9 +5,18 @@
5
5
  'use strict';
6
6
 
7
7
  const MongooseConnection = require('../../connection');
8
- const STATES = require('../../connectionstate');
9
- const immediate = require('../../helpers/immediate');
8
+ const MongooseError = require('../../error/index');
9
+ const STATES = require('../../connectionState');
10
+ const mongodb = require('mongodb');
11
+ const pkg = require('../../../package.json');
12
+ const processConnectionOptions = require('../../helpers/processConnectionOptions');
10
13
  const setTimeout = require('../../helpers/timers').setTimeout;
14
+ const utils = require('../../utils');
15
+ const Schema = require('../../schema');
16
+
17
+ // Snapshot the native Date constructor to ensure Date.now()
18
+ // bypasses timer mocks such as those set up by useFakeTimers().
19
+ const Date = globalThis.Date;
11
20
 
12
21
  /**
13
22
  * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.
@@ -19,6 +28,11 @@ const setTimeout = require('../../helpers/timers').setTimeout;
19
28
  function NativeConnection() {
20
29
  MongooseConnection.apply(this, arguments);
21
30
  this._listening = false;
31
+ // Tracks the last time (as unix timestamp) the connection received a
32
+ // serverHeartbeatSucceeded or serverHeartbeatFailed event from the underlying MongoClient.
33
+ // If we haven't received one in a while (like due to a frozen AWS Lambda container) then
34
+ // `readyState` is likely stale.
35
+ this._lastHeartbeatAt = null;
22
36
  }
23
37
 
24
38
  /**
@@ -42,10 +56,9 @@ Object.setPrototypeOf(NativeConnection.prototype, MongooseConnection.prototype);
42
56
  *
43
57
  * **Note:** Calling `close()` on a `useDb()` connection will close the base connection as well.
44
58
  *
45
- * @param {String} name The database name
46
- * @param {Object} [options]
47
- * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
48
- * @param {Boolean} [options.noListener=false] If true, the new connection object won't listen to any events on the base connection. This is better for memory usage in cases where you're calling `useDb()` for every request.
59
+ * @param {string} name The database name
60
+ * @param {object} [options]
61
+ * @param {boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
49
62
  * @return {Connection} New Connection Object
50
63
  * @api public
51
64
  */
@@ -92,29 +105,24 @@ NativeConnection.prototype.useDb = function(name, options) {
92
105
  if (this.db && this._readyState === STATES.connected) {
93
106
  wireup();
94
107
  } else {
95
- this.once('connected', wireup);
108
+ this._queue.push({ fn: wireup });
96
109
  }
97
110
 
98
111
  function wireup() {
99
112
  newConn.client = _this.client;
100
- const _opts = {};
101
- if (options.hasOwnProperty('noListener')) {
102
- _opts.noListener = options.noListener;
103
- }
104
- newConn.db = _this.client.db(name, _opts);
113
+ newConn.db = _this.client.db(name);
114
+ newConn._lastHeartbeatAt = _this._lastHeartbeatAt;
105
115
  newConn.onOpen();
106
116
  }
107
117
 
108
118
  newConn.name = name;
109
119
 
110
120
  // push onto the otherDbs stack, this is used when state changes
111
- if (options.noListener !== true) {
112
- this.otherDbs.push(newConn);
113
- }
121
+ this.otherDbs.push(newConn);
114
122
  newConn.otherDbs.push(this);
115
123
 
116
124
  // push onto the relatedDbs cache, this is used when state changes
117
- if (options && options.useCache) {
125
+ if (options?.useCache) {
118
126
  this.relatedDbs[newConn.name] = newConn;
119
127
  newConn.relatedDbs = this.relatedDbs;
120
128
  }
@@ -122,18 +130,65 @@ NativeConnection.prototype.useDb = function(name, options) {
122
130
  return newConn;
123
131
  };
124
132
 
133
+ /**
134
+ * Runs a [db-level aggregate()](https://www.mongodb.com/docs/manual/reference/method/db.aggregate/) on this connection's underlying `db`
135
+ *
136
+ * @param {Array} pipeline
137
+ * @param {object} [options]
138
+ */
139
+
140
+ NativeConnection.prototype.aggregate = function aggregate(pipeline, options) {
141
+ return new this.base.Aggregate(null, this).append(pipeline).option(options ?? {});
142
+ };
143
+
144
+ /**
145
+ * Removes the database connection with the given name created with `useDb()`.
146
+ *
147
+ * Throws an error if the database connection was not found.
148
+ *
149
+ * #### Example:
150
+ *
151
+ * // Connect to `initialdb` first
152
+ * const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/initialdb').asPromise();
153
+ *
154
+ * // Creates an un-cached connection to `mydb`
155
+ * const db = conn.useDb('mydb');
156
+ *
157
+ * // Closes `db`, and removes `db` from `conn.relatedDbs` and `conn.otherDbs`
158
+ * await conn.removeDb('mydb');
159
+ *
160
+ * @method removeDb
161
+ * @memberOf Connection
162
+ * @param {string} name The database name
163
+ * @return {Connection} this
164
+ */
165
+
166
+ NativeConnection.prototype.removeDb = function removeDb(name) {
167
+ const dbs = this.otherDbs.filter(db => db.name === name);
168
+ if (!dbs.length) {
169
+ throw new MongooseError(`No connections to database "${name}" found`);
170
+ }
171
+
172
+ for (const db of dbs) {
173
+ db._closeCalled = true;
174
+ db._destroyCalled = true;
175
+ db._readyState = STATES.disconnected;
176
+ db.$wasForceClosed = true;
177
+ }
178
+ delete this.relatedDbs[name];
179
+ this.otherDbs = this.otherDbs.filter(db => db.name !== name);
180
+ };
181
+
125
182
  /**
126
183
  * Closes the connection
127
184
  *
128
- * @param {Boolean} [force]
129
- * @param {Function} [fn]
185
+ * @param {boolean} [force]
130
186
  * @return {Connection} this
131
187
  * @api private
132
188
  */
133
189
 
134
- NativeConnection.prototype.doClose = function(force, fn) {
190
+ NativeConnection.prototype.doClose = async function doClose(force) {
135
191
  if (this.client == null) {
136
- immediate(() => fn());
137
192
  return this;
138
193
  }
139
194
 
@@ -144,20 +199,323 @@ NativeConnection.prototype.doClose = function(force, fn) {
144
199
  }
145
200
 
146
201
  if (skipCloseClient) {
147
- immediate(() => fn());
148
202
  return this;
149
203
  }
150
204
 
151
- this.client.close(force, (err, res) => {
152
- // Defer because the driver will wait at least 1ms before finishing closing
153
- // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030.
154
- // If there's queued operations, you may still get some background work
155
- // after the callback is called.
156
- setTimeout(() => fn(err, res), 1);
157
- });
205
+ await this.client.close(force);
206
+ // Defer because the driver will wait at least 1ms before finishing closing
207
+ // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030.
208
+ // If there's queued operations, you may still get some background work
209
+ // after the callback is called.
210
+ await new Promise(resolve => setTimeout(resolve, 1));
211
+
158
212
  return this;
159
213
  };
160
214
 
215
+ /**
216
+ * Implementation of `listDatabases()` for MongoDB driver
217
+ *
218
+ * @return {Promise}
219
+ * @api public
220
+ */
221
+
222
+ NativeConnection.prototype.listDatabases = async function listDatabases() {
223
+ await this._waitForConnect();
224
+
225
+ return await this.db.admin().listDatabases();
226
+ };
227
+
228
+ /*!
229
+ * ignore
230
+ */
231
+
232
+ NativeConnection.prototype.createClient = async function createClient(uri, options) {
233
+ if (typeof uri !== 'string') {
234
+ throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
235
+ `string, got "${typeof uri}". Make sure the first parameter to ` +
236
+ '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
237
+ }
238
+
239
+ if (this._destroyCalled) {
240
+ throw new MongooseError(
241
+ 'Connection has been closed and destroyed, and cannot be used for re-opening the connection. ' +
242
+ 'Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.'
243
+ );
244
+ }
245
+
246
+ if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
247
+ if (this._connectionString !== uri) {
248
+ throw new MongooseError('Can\'t call `openUri()` on an active connection with ' +
249
+ 'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' +
250
+ 'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');
251
+ }
252
+ }
253
+
254
+ options = processConnectionOptions(uri, options);
255
+
256
+ if (options) {
257
+
258
+ const autoIndex = options.config?.autoIndex ?? options.autoIndex;
259
+ if (autoIndex != null) {
260
+ this.config.autoIndex = autoIndex !== false;
261
+ delete options.config;
262
+ delete options.autoIndex;
263
+ }
264
+
265
+ if ('autoCreate' in options) {
266
+ this.config.autoCreate = !!options.autoCreate;
267
+ delete options.autoCreate;
268
+ }
269
+
270
+ if ('sanitizeFilter' in options) {
271
+ this.config.sanitizeFilter = options.sanitizeFilter;
272
+ delete options.sanitizeFilter;
273
+ }
274
+
275
+ if ('autoSearchIndex' in options) {
276
+ this.config.autoSearchIndex = options.autoSearchIndex;
277
+ delete options.autoSearchIndex;
278
+ }
279
+
280
+ if ('bufferTimeoutMS' in options) {
281
+ this.config.bufferTimeoutMS = options.bufferTimeoutMS;
282
+ delete options.bufferTimeoutMS;
283
+ }
284
+
285
+ // Backwards compat
286
+ if (options.user || options.pass) {
287
+ options.auth = options.auth || {};
288
+ options.auth.username = options.user;
289
+ options.auth.password = options.pass;
290
+
291
+ this.user = options.user;
292
+ this.pass = options.pass;
293
+ }
294
+ delete options.user;
295
+ delete options.pass;
296
+
297
+ if (options.bufferCommands != null) {
298
+ this.config.bufferCommands = options.bufferCommands;
299
+ delete options.bufferCommands;
300
+ }
301
+ } else {
302
+ options = {};
303
+ }
304
+
305
+ this._connectionOptions = options;
306
+ const dbName = options.dbName;
307
+ if (dbName != null) {
308
+ this.$dbName = dbName;
309
+ }
310
+ delete options.dbName;
311
+
312
+ if (!utils.hasUserDefinedProperty(options, 'driverInfo')) {
313
+ options.driverInfo = {
314
+ name: 'Mongoose',
315
+ version: pkg.version
316
+ };
317
+ }
318
+
319
+ const { schemaMap, encryptedFieldsMap } = this._buildEncryptionSchemas();
320
+
321
+ if ((utils.hasOwnKeys(schemaMap) || utils.hasOwnKeys(encryptedFieldsMap)) && !options.autoEncryption) {
322
+ throw new Error('Must provide `autoEncryption` when connecting with encrypted schemas.');
323
+ }
324
+
325
+ if (utils.hasOwnKeys(schemaMap)) {
326
+ options.autoEncryption.schemaMap = schemaMap;
327
+ }
328
+
329
+ if (utils.hasOwnKeys(encryptedFieldsMap)) {
330
+ options.autoEncryption.encryptedFieldsMap = encryptedFieldsMap;
331
+ }
332
+
333
+ this.readyState = STATES.connecting;
334
+ this._connectionString = uri;
335
+
336
+ let client;
337
+ try {
338
+ client = new mongodb.MongoClient(uri, options);
339
+ } catch (error) {
340
+ this.readyState = STATES.disconnected;
341
+ throw error;
342
+ }
343
+ this.client = client;
344
+
345
+ client.setMaxListeners(0);
346
+ await client.connect();
347
+
348
+ _setClient(this, client, options, dbName);
349
+
350
+ for (const db of this.otherDbs) {
351
+ _setClient(db, client, {}, db.name);
352
+ }
353
+ return this;
354
+ };
355
+
356
+ /**
357
+ * Given a connection, which may or may not have encrypted models, build
358
+ * a schemaMap and/or an encryptedFieldsMap for the connection, combining all models
359
+ * into a single schemaMap and encryptedFields map.
360
+ *
361
+ * @returns {object} the generated schemaMap and encryptedFieldsMap
362
+ */
363
+ NativeConnection.prototype._buildEncryptionSchemas = function() {
364
+ const qeMappings = {};
365
+ const csfleMappings = {};
366
+
367
+ const encryptedModels = Object.values(this.models).filter(model => model.schema._hasEncryptedFields());
368
+
369
+ // If discriminators are configured for the collection, there might be multiple models
370
+ // pointing to the same namespace. For this scenario, we merge all the schemas for each namespace
371
+ // into a single schema and then generate a schemaMap/encryptedFieldsMap for the combined schema.
372
+ for (const model of encryptedModels) {
373
+ const { schema, collection: { collectionName } } = model;
374
+ const namespace = `${this.$dbName}.${collectionName}`;
375
+ const mappings = schema.encryptionType() === 'csfle' ? csfleMappings : qeMappings;
376
+
377
+ mappings[namespace] ??= new Schema({}, { encryptionType: schema.encryptionType() });
378
+
379
+ const isNonRootDiscriminator = schema.discriminatorMapping && !schema.discriminatorMapping.isRoot;
380
+ if (isNonRootDiscriminator) {
381
+ const rootSchema = schema._baseSchema;
382
+ schema.eachPath((pathname) => {
383
+ if (rootSchema.path(pathname)) return;
384
+ if (!mappings[namespace]._hasEncryptedField(pathname)) return;
385
+
386
+ throw new Error(`Cannot have duplicate keys in discriminators with encryption. key=${pathname}`);
387
+ });
388
+ }
389
+
390
+ mappings[namespace].add(schema);
391
+ }
392
+
393
+ const schemaMap = Object.fromEntries(Object.entries(csfleMappings).map(
394
+ ([namespace, schema]) => ([namespace, schema._buildSchemaMap()])
395
+ ));
396
+
397
+ const encryptedFieldsMap = Object.fromEntries(Object.entries(qeMappings).map(
398
+ ([namespace, schema]) => ([namespace, schema._buildEncryptedFields()])
399
+ ));
400
+
401
+ return {
402
+ schemaMap, encryptedFieldsMap
403
+ };
404
+ };
405
+
406
+ /*!
407
+ * ignore
408
+ */
409
+
410
+ NativeConnection.prototype.setClient = function setClient(client) {
411
+ if (!(client instanceof mongodb.MongoClient)) {
412
+ throw new MongooseError('Must call `setClient()` with an instance of MongoClient');
413
+ }
414
+ if (this.readyState !== STATES.disconnected) {
415
+ throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');
416
+ }
417
+ if (client.topology == null) {
418
+ throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.');
419
+ }
420
+
421
+ this._connectionString = client.s.url;
422
+ _setClient(this, client, {}, client.s.options.dbName);
423
+
424
+ for (const model of Object.values(this.models)) {
425
+ // Errors handled internally, so safe to ignore error
426
+ model.init().catch(function $modelInitNoop() {});
427
+ }
428
+
429
+ return this;
430
+ };
431
+
432
+ /*!
433
+ * ignore
434
+ */
435
+
436
+ function _setClient(conn, client, options, dbName) {
437
+ const db = dbName != null ? client.db(dbName) : client.db();
438
+ conn.db = db;
439
+ conn.client = client;
440
+ conn.host = client?.s?.options?.hosts?.[0]?.host;
441
+ conn.port = client?.s?.options?.hosts?.[0]?.port;
442
+ conn.name = dbName != null ? dbName : db.databaseName;
443
+ conn._closeCalled = client._closeCalled;
444
+
445
+ const _handleReconnect = () => {
446
+ // If we aren't disconnected, we assume this reconnect is due to a
447
+ // socket timeout. If there's no activity on a socket for
448
+ // `socketTimeoutMS`, the driver will attempt to reconnect and emit
449
+ // this event.
450
+ if (conn.readyState !== STATES.connected) {
451
+ conn.readyState = STATES.connected;
452
+ conn.emit('reconnect');
453
+ conn.emit('reconnected');
454
+ conn.onOpen();
455
+ }
456
+ };
457
+
458
+ const type = client?.topology?.description?.type || '';
459
+
460
+ if (type === 'Single') {
461
+ client.on('serverDescriptionChanged', ev => {
462
+ const newDescription = ev.newDescription;
463
+ if (newDescription.type === 'Unknown') {
464
+ conn.readyState = STATES.disconnected;
465
+ } else {
466
+ _handleReconnect();
467
+ }
468
+ });
469
+ } else if (type.startsWith('ReplicaSet')) {
470
+ client.on('topologyDescriptionChanged', ev => {
471
+ // Emit disconnected if we've lost connectivity to the primary
472
+ const description = ev.newDescription;
473
+ if (conn.readyState === STATES.connected && description.type !== 'ReplicaSetWithPrimary') {
474
+ // Implicitly emits 'disconnected'
475
+ conn.readyState = STATES.disconnected;
476
+ } else if (conn.readyState === STATES.disconnected && description.type === 'ReplicaSetWithPrimary') {
477
+ _handleReconnect();
478
+ }
479
+ });
480
+ }
481
+
482
+ conn._lastHeartbeatAt = null;
483
+
484
+ client.on('serverHeartbeatSucceeded', () => {
485
+ conn._lastHeartbeatAt = Date.now();
486
+ for (const otherDb of conn.otherDbs) {
487
+ otherDb._lastHeartbeatAt = conn._lastHeartbeatAt;
488
+ }
489
+ // Flush buffered operations if the connection is no longer stale (gh-16183)
490
+ if (conn._queue.length > 0 && conn.readyState === STATES.connected) {
491
+ conn._flushQueue();
492
+ }
493
+ for (const otherDb of conn.otherDbs) {
494
+ if (otherDb._queue.length > 0 && otherDb.readyState === STATES.connected) {
495
+ otherDb._flushQueue();
496
+ }
497
+ }
498
+ for (const collection of Object.values(conn.collections)) {
499
+ if (collection.buffer) {
500
+ collection.onOpen();
501
+ }
502
+ }
503
+ });
504
+
505
+ if (options.monitorCommands) {
506
+ client.on('commandStarted', (data) => conn.emit('commandStarted', data));
507
+ client.on('commandFailed', (data) => conn.emit('commandFailed', data));
508
+ client.on('commandSucceeded', (data) => conn.emit('commandSucceeded', data));
509
+ }
510
+
511
+ conn.onOpen();
512
+
513
+ for (const i in conn.collections) {
514
+ if (Object.hasOwn(conn.collections, i)) {
515
+ conn.collections[i].onOpen();
516
+ }
517
+ }
518
+ }
161
519
 
162
520
  /*!
163
521
  * Module exports.
@@ -4,9 +4,7 @@
4
4
 
5
5
  'use strict';
6
6
 
7
- exports.Binary = require('./binary');
7
+ exports.BulkWriteResult = require('./bulkWriteResult');
8
8
  exports.Collection = require('./collection');
9
- exports.Decimal128 = require('./decimal128');
10
- exports.ObjectId = require('./objectid');
11
- exports.ReadPreference = require('./ReadPreference');
12
- exports.getConnection = () => require('./connection');
9
+ exports.Connection = require('./connection');
10
+ exports.ClientEncryption = require('mongodb').ClientEncryption;
@@ -4,13 +4,14 @@
4
4
 
5
5
  'use strict';
6
6
 
7
- const MongooseError = require('./');
7
+ const MongooseError = require('./mongooseError');
8
8
 
9
+ /**
10
+ * MissingSchema Error constructor.
11
+ */
9
12
 
10
13
  class MissingSchemaError extends MongooseError {
11
- /**
12
- * MissingSchema Error constructor.
13
- */
14
+
14
15
  constructor() {
15
16
  super('Schema hasn\'t been registered for document.\n'
16
17
  + 'Use mongoose.Document(name, schema)');
@@ -0,0 +1,44 @@
1
+ /*!
2
+ * Module dependencies.
3
+ */
4
+
5
+ 'use strict';
6
+
7
+ const MongooseError = require('./mongooseError');
8
+
9
+
10
+ /**
11
+ * If the underwriting `bulkWrite()` for `bulkSave()` succeeded, but wasn't able to update or
12
+ * insert all documents, we throw this error.
13
+ *
14
+ * @api private
15
+ */
16
+
17
+ class MongooseBulkSaveIncompleteError extends MongooseError {
18
+ constructor(modelName, documents, bulkWriteResult) {
19
+ const matchedCount = bulkWriteResult?.matchedCount ?? 0;
20
+ const insertedCount = bulkWriteResult?.insertedCount ?? 0;
21
+ let preview = documents.map(doc => doc._id).join(', ');
22
+ if (preview.length > 100) {
23
+ preview = preview.slice(0, 100) + '...';
24
+ }
25
+
26
+ const numDocumentsNotUpdated = documents.length - matchedCount - insertedCount;
27
+ super(`${modelName}.bulkSave() was not able to update ${numDocumentsNotUpdated} of the given documents due to incorrect version or optimistic concurrency, document ids: ${preview}`);
28
+
29
+ this.modelName = modelName;
30
+ this.documents = documents;
31
+ this.bulkWriteResult = bulkWriteResult;
32
+ this.numDocumentsNotUpdated = numDocumentsNotUpdated;
33
+ }
34
+ }
35
+
36
+ Object.defineProperty(MongooseBulkSaveIncompleteError.prototype, 'name', {
37
+ value: 'MongooseBulkSaveIncompleteError'
38
+ });
39
+
40
+ /*!
41
+ * exports
42
+ */
43
+
44
+ module.exports = MongooseBulkSaveIncompleteError;
package/lib/error/cast.js CHANGED
@@ -10,8 +10,8 @@ const util = require('util');
10
10
  /**
11
11
  * Casting Error constructor.
12
12
  *
13
- * @param {String} type
14
- * @param {String} value
13
+ * @param {string} type
14
+ * @param {string} value
15
15
  * @inherits MongooseError
16
16
  * @api private
17
17
  */
@@ -20,10 +20,9 @@ class CastError extends MongooseError {
20
20
  constructor(type, value, path, reason, schemaType) {
21
21
  // If no args, assume we'll `init()` later.
22
22
  if (arguments.length > 0) {
23
- const stringValue = getStringValue(value);
24
23
  const valueType = getValueType(value);
25
24
  const messageFormat = getMessageFormat(schemaType);
26
- const msg = formatMessage(null, type, stringValue, path, messageFormat, valueType, reason);
25
+ const msg = formatMessage(null, type, value, path, messageFormat, valueType, reason);
27
26
  super(msg);
28
27
  this.init(type, value, path, reason, schemaType);
29
28
  } else {
@@ -43,6 +42,7 @@ class CastError extends MongooseError {
43
42
  message: this.message
44
43
  };
45
44
  }
45
+
46
46
  /*!
47
47
  * ignore
48
48
  */
@@ -76,9 +76,8 @@ class CastError extends MongooseError {
76
76
  * ignore
77
77
  */
78
78
  setModel(model) {
79
- this.model = model;
80
- this.message = formatMessage(model, this.kind, this.stringValue, this.path,
81
- this.messageFormat, this.valueType);
79
+ this.message = formatMessage(model, this.kind, this.value, this.path,
80
+ this.messageFormat, this.valueType, this.reason);
82
81
  }
83
82
  }
84
83
 
@@ -111,10 +110,8 @@ function getValueType(value) {
111
110
  }
112
111
 
113
112
  function getMessageFormat(schemaType) {
114
- const messageFormat = schemaType &&
115
- schemaType.options &&
116
- schemaType.options.cast || null;
117
- if (typeof messageFormat === 'string') {
113
+ const messageFormat = schemaType?._castErrorMessage || null;
114
+ if (typeof messageFormat === 'string' || typeof messageFormat === 'function') {
118
115
  return messageFormat;
119
116
  }
120
117
  }
@@ -123,30 +120,42 @@ function getMessageFormat(schemaType) {
123
120
  * ignore
124
121
  */
125
122
 
126
- function formatMessage(model, kind, stringValue, path, messageFormat, valueType, reason) {
127
- if (messageFormat != null) {
128
- let ret = messageFormat.
129
- replace('{KIND}', kind).
130
- replace('{VALUE}', stringValue).
131
- replace('{PATH}', path);
123
+ function formatMessage(model, kind, value, path, messageFormat, valueType, reason) {
124
+ if (typeof messageFormat === 'string') {
125
+ const stringValue = getStringValue(value);
126
+ let ret = messageFormat
127
+ .replace('{KIND}', kind)
128
+ .replace('{VALUE}', stringValue)
129
+ .replace('{PATH}', path);
130
+
132
131
  if (model != null) {
133
132
  ret = ret.replace('{MODEL}', model.modelName);
134
133
  }
135
134
 
136
135
  return ret;
136
+ } else if (typeof messageFormat === 'function') {
137
+ return messageFormat(value, path, model, kind);
137
138
  } else {
139
+ const stringValue = getStringValue(value);
138
140
  const valueTypeMsg = valueType ? ' (type ' + valueType + ')' : '';
141
+
139
142
  let ret = 'Cast to ' + kind + ' failed for value ' +
140
143
  stringValue + valueTypeMsg + ' at path "' + path + '"';
144
+
141
145
  if (model != null) {
142
146
  ret += ' for model "' + model.modelName + '"';
143
147
  }
144
- if (reason != null &&
145
- typeof reason.constructor === 'function' &&
146
- reason.constructor.name !== 'AssertionError' &&
147
- reason.constructor.name !== 'Error') {
148
+
149
+ if (
150
+ reason != null &&
151
+ typeof reason.constructor === 'function' &&
152
+ reason.constructor.name !== 'AssertionError' &&
153
+ reason.constructor.name !== 'Error' &&
154
+ reason.constructor.name !== 'BSONError'
155
+ ) {
148
156
  ret += ' because of "' + reason.constructor.name + '"';
149
157
  }
158
+
150
159
  return ret;
151
160
  }
152
161
  }
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ const MongooseError = require('./mongooseError');
4
+
5
+ /**
6
+ * createCollections Error constructor
7
+ *
8
+ * @param {string} message
9
+ * @param {string} errorsMap
10
+ * @inherits MongooseError
11
+ * @api private
12
+ */
13
+
14
+ class CreateCollectionsError extends MongooseError {
15
+ constructor(message, errorsMap) {
16
+ super(message);
17
+ this.errors = errorsMap;
18
+ }
19
+ }
20
+
21
+ Object.defineProperty(CreateCollectionsError.prototype, 'name', {
22
+ value: 'CreateCollectionsError'
23
+ });
24
+
25
+ module.exports = CreateCollectionsError;
26
+