@datanimbus/mongoose 9.13.1 → 9.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -9,12 +9,15 @@ exports.Array = require('./array');
9
9
  exports.Buffer = require('./buffer');
10
10
 
11
11
  exports.Document = // @deprecate
12
- exports.Embedded = require('./ArraySubdocument');
12
+ exports.Embedded = require('./arraySubdocument');
13
13
 
14
- exports.DocumentArray = require('./DocumentArray');
14
+ exports.DocumentArray = require('./documentArray');
15
+ exports.Double = require('./double');
15
16
  exports.Decimal128 = require('./decimal128');
16
17
  exports.ObjectId = require('./objectid');
17
18
 
18
19
  exports.Map = require('./map');
19
20
 
20
21
  exports.Subdocument = require('./subdocument');
22
+
23
+ exports.UUID = require('./uuid');
package/lib/types/map.js CHANGED
@@ -4,11 +4,14 @@ const Mixed = require('../schema/mixed');
4
4
  const MongooseError = require('../error/mongooseError');
5
5
  const clone = require('../helpers/clone');
6
6
  const deepEqual = require('../utils').deepEqual;
7
+ const isMongooseArray = require('../utils').isMongooseArray;
7
8
  const getConstructorName = require('../helpers/getConstructorName');
8
9
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
10
+ const isMongooseDocument = require('../helpers/isMongooseDocument');
9
11
  const util = require('util');
10
12
  const specialProperties = require('../helpers/specialProperties');
11
13
  const isBsonType = require('../helpers/isBsonType');
14
+ const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths');
12
15
 
13
16
  const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
14
17
 
@@ -19,10 +22,10 @@ const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
19
22
  class MongooseMap extends Map {
20
23
  constructor(v, path, doc, schemaType) {
21
24
  if (getConstructorName(v) === 'Object') {
22
- v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
25
+ v = Object.keys(v).map(key => [key, v[key]]);
23
26
  }
24
27
  super(v);
25
- this.$__parent = doc != null && doc.$__ != null ? doc : null;
28
+ this.$__parent = doc?.$__ != null ? doc : null;
26
29
  this.$__path = path;
27
30
  this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType;
28
31
 
@@ -34,7 +37,7 @@ class MongooseMap extends Map {
34
37
 
35
38
  super.set(key, value);
36
39
 
37
- if (value != null && value.$isSingleNested) {
40
+ if (value?.$isSingleNested) {
38
41
  value.$basePath = this.$__path + '.' + key;
39
42
  }
40
43
  }
@@ -52,7 +55,7 @@ class MongooseMap extends Map {
52
55
  */
53
56
 
54
57
  get(key, options) {
55
- if (isBsonType(key, 'ObjectID')) {
58
+ if (isBsonType(key, 'ObjectId')) {
56
59
  key = key.toString();
57
60
  }
58
61
 
@@ -63,15 +66,38 @@ class MongooseMap extends Map {
63
66
  return this.$__schemaType.applyGetters(super.get(key), this.$__parent);
64
67
  }
65
68
 
69
+ /**
70
+ * Overwrites native Map's `has()` function to support ObjectIds as keys.
71
+ *
72
+ * @api public
73
+ * @method has
74
+ * @memberOf Map
75
+ */
76
+
77
+ has(key) {
78
+ if (isBsonType(key, 'ObjectId')) {
79
+ key = key.toString();
80
+ }
81
+
82
+ return super.has(key);
83
+ }
84
+
66
85
  /**
67
86
  * Overwrites native Map's `set()` function to support setters, `populate()`,
68
87
  * and change tracking. Note that Mongoose maps _only_ support strings and
69
88
  * ObjectIds as keys.
70
89
  *
90
+ * Keys also cannot:
91
+ * - be named after special properties `prototype`, `constructor`, and `__proto__`
92
+ * - start with a dollar sign (`$`)
93
+ * - contain any dots (`.`)
94
+ *
71
95
  * #### Example:
72
96
  *
73
97
  * doc.myMap.set('test', 42); // works
74
98
  * doc.myMap.set({ obj: 42 }, 42); // Throws "Mongoose maps only support string keys"
99
+ * doc.myMap.set(10, 42); // Throws "Mongoose maps only support string keys"
100
+ * doc.myMap.set("$test", 42); // Throws "Mongoose maps do not support keys that start with "$", got "$test""
75
101
  *
76
102
  * @api public
77
103
  * @method set
@@ -79,7 +105,7 @@ class MongooseMap extends Map {
79
105
  */
80
106
 
81
107
  set(key, value) {
82
- if (isBsonType(key, 'ObjectID')) {
108
+ if (isBsonType(key, 'ObjectId')) {
83
109
  key = key.toString();
84
110
  }
85
111
 
@@ -98,7 +124,7 @@ class MongooseMap extends Map {
98
124
 
99
125
  let _fullPath;
100
126
  const parent = this.$__parent;
101
- const populated = parent != null && parent.$__ && parent.$__.populated ?
127
+ const populated = parent?.$__?.populated ?
102
128
  parent.$populated(fullPath.call(this), true) || parent.$populated(this.$__path, true) :
103
129
  null;
104
130
  const priorVal = this.get(key);
@@ -112,23 +138,23 @@ class MongooseMap extends Map {
112
138
  }
113
139
  if (Array.isArray(value) && this.$__schemaType.$isMongooseArray) {
114
140
  value = value.map(v => {
115
- if (v.$__ == null) {
141
+ if (!isMongooseDocument(v)) {
116
142
  v = new populated.options[populateModelSymbol](v);
117
143
  }
118
144
  // Doesn't support single nested "in-place" populate
119
- v.$__.wasPopulated = { value: v._id };
145
+ v.$__.wasPopulated = { value: v._doc._id };
120
146
  return v;
121
147
  });
122
- } else {
123
- if (value.$__ == null) {
148
+ } else if (value != null) {
149
+ if (!isMongooseDocument(value)) {
124
150
  value = new populated.options[populateModelSymbol](value);
125
151
  }
126
152
  // Doesn't support single nested "in-place" populate
127
- value.$__.wasPopulated = { value: value._id };
153
+ value.$__.wasPopulated = { value: value._doc._id };
128
154
  }
129
155
  } else {
130
156
  try {
131
- const options = this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested ?
157
+ const options = this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested || this.$__schemaType.$isMongooseArray || this.$__schemaType.$isSchemaMap ?
132
158
  { path: fullPath.call(this) } :
133
159
  null;
134
160
  value = this.$__schemaType.applySetters(
@@ -139,7 +165,7 @@ class MongooseMap extends Map {
139
165
  options
140
166
  );
141
167
  } catch (error) {
142
- if (this.$__parent != null && this.$__parent.$__ != null) {
168
+ if (this.$__parent?.$__ != null) {
143
169
  this.$__parent.invalidate(fullPath.call(this), error);
144
170
  return;
145
171
  }
@@ -149,8 +175,19 @@ class MongooseMap extends Map {
149
175
 
150
176
  super.set(key, value);
151
177
 
152
- if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) {
153
- parent.markModified(fullPath.call(this));
178
+ if (parent?.$__ != null && !deepEqual(value, priorVal)) {
179
+ const path = fullPath.call(this);
180
+ parent.markModified(path);
181
+ // Replacing the whole array means later push(), pull() or addToSet() calls must not be sent as
182
+ // atomics against the array that was in the database, same as Document#$set re: gh-1126
183
+ if (isMongooseArray(value)) {
184
+ value._registerAtomic('$set', value);
185
+ }
186
+ // If overwriting the full document array or subdoc, make sure to clean up any paths that were modified
187
+ // before re: #15108
188
+ if (this.$__schemaType.$isMongooseDocumentArray || this.$__schemaType.$isSingleNested) {
189
+ cleanModifiedSubpaths(parent, path);
190
+ }
154
191
  }
155
192
 
156
193
  // Delay calculating full path unless absolutely necessary, because string
@@ -189,7 +226,7 @@ class MongooseMap extends Map {
189
226
  */
190
227
 
191
228
  delete(key) {
192
- if (isBsonType(key, 'ObjectID')) {
229
+ if (isBsonType(key, 'ObjectId')) {
193
230
  key = key.toString();
194
231
  }
195
232
 
@@ -210,7 +247,7 @@ class MongooseMap extends Map {
210
247
  }
211
248
 
212
249
  toObject(options) {
213
- if (options && options.flattenMaps) {
250
+ if (options?.flattenMaps) {
214
251
  const ret = {};
215
252
  const keys = this.keys();
216
253
  for (const key of keys) {
@@ -227,23 +264,23 @@ class MongooseMap extends Map {
227
264
  }
228
265
 
229
266
  /**
230
- * Converts this map to a native JavaScript Map for `JSON.stringify()`. Set
231
- * the `flattenMaps` option to convert this map to a POJO instead.
267
+ * Converts this map to a POJO for `JSON.stringify()`. Set the `flattenMaps`
268
+ * option to `false` to convert this map to a native JavaScript Map instead.
232
269
  *
233
270
  * #### Example:
234
271
  *
235
- * doc.myMap.toJSON() instanceof Map; // true
236
- * doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false
272
+ * doc.myMap.toJSON() instanceof Map; // false
273
+ * doc.myMap.toJSON({ flattenMaps: false }) instanceof Map; // true
237
274
  *
238
275
  * @api public
239
276
  * @method toJSON
240
- * @param {Object} [options]
241
- * @param {Boolean} [options.flattenMaps=false] set to `true` to convert the map to a POJO rather than a native JavaScript map
277
+ * @param {object} [options]
278
+ * @param {boolean} [options.flattenMaps=true] set to `false` to convert the map to a native JavaScript Map rather than a POJO
242
279
  * @memberOf Map
243
280
  */
244
281
 
245
282
  toJSON(options) {
246
- if (typeof (options && options.flattenMaps) === 'boolean' ? options.flattenMaps : true) {
283
+ if (typeof options?.flattenMaps === 'boolean' ? options.flattenMaps : true) {
247
284
  const ret = {};
248
285
  const keys = this.keys();
249
286
  for (const key of keys) {
@@ -331,7 +368,7 @@ Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', {
331
368
  /**
332
369
  * Since maps are stored as objects under the hood, keys must be strings
333
370
  * and can't contain any invalid characters
334
- * @param {String} key
371
+ * @param {string} key
335
372
  * @api private
336
373
  */
337
374
 
@@ -10,7 +10,7 @@
10
10
 
11
11
  'use strict';
12
12
 
13
- const ObjectId = require('../driver').get().ObjectId;
13
+ const ObjectId = require('mongodb/lib/bson').ObjectId;
14
14
  const objectIdSymbol = require('../helpers/symbols').objectIdSymbol;
15
15
 
16
16
  /**
@@ -30,7 +30,7 @@ Object.defineProperty(ObjectId.prototype, '_id', {
30
30
  * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299
31
31
  */
32
32
 
33
- if (!ObjectId.prototype.hasOwnProperty('valueOf')) {
33
+ if (!Object.hasOwn(ObjectId.prototype, 'valueOf')) {
34
34
  ObjectId.prototype.valueOf = function objectIdValueOf() {
35
35
  return this.toString();
36
36
  };
@@ -1,9 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const Document = require('../document');
4
- const immediate = require('../helpers/immediate');
5
4
  const internalToObjectOptions = require('../options').internalToObjectOptions;
6
- const promiseOrCallback = require('../helpers/promiseOrCallback');
7
5
  const util = require('util');
8
6
  const utils = require('../utils');
9
7
 
@@ -16,7 +14,7 @@ module.exports = Subdocument;
16
14
  * @api private
17
15
  */
18
16
 
19
- function Subdocument(value, fields, parent, skipId, options) {
17
+ function Subdocument(value, fields, parent, options) {
20
18
  if (parent != null) {
21
19
  // If setting a nested path, should copy isNew from parent re: gh-7048
22
20
  const parentOptions = { isNew: parent.isNew };
@@ -25,12 +23,16 @@ function Subdocument(value, fields, parent, skipId, options) {
25
23
  }
26
24
  options = Object.assign(parentOptions, options);
27
25
  }
28
- if (options != null && options.path != null) {
26
+ if (options?.path != null) {
29
27
  this.$basePath = options.path;
30
28
  }
31
- Document.call(this, value, fields, skipId, options);
29
+ Document.call(this, value, fields, options);
32
30
 
33
- delete this.$__.priorDoc;
31
+ // `priorDoc` is only needed during construction, so release the reference.
32
+ // Set to undefined rather than `delete` to keep `$__` out of dictionary mode.
33
+ if (this.$__.priorDoc !== undefined) {
34
+ this.$__.priorDoc = undefined;
35
+ }
34
36
  }
35
37
 
36
38
  Subdocument.prototype = Object.create(Document.prototype);
@@ -62,16 +64,16 @@ Subdocument.prototype.toBSON = function() {
62
64
  *
63
65
  * _This is a no-op. Does not actually save the doc to the db._
64
66
  *
65
- * @param {Function} [fn]
67
+ * @param {object} [options]
68
+ * @param {boolean} [options.suppressWarning=false] If `true`, suppress the warning about calling `save()` on a subdoc.
69
+ * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
70
+ * @param {boolean} [options.middleware.pre=true] set to `false` to skip only pre hooks
71
+ * @param {boolean} [options.middleware.post=true] set to `false` to skip only post hooks
66
72
  * @return {Promise} resolved Promise
67
73
  * @api private
68
74
  */
69
75
 
70
- Subdocument.prototype.save = function(options, fn) {
71
- if (typeof options === 'function') {
72
- fn = options;
73
- options = {};
74
- }
76
+ Subdocument.prototype.save = async function save(options) {
75
77
  options = options || {};
76
78
 
77
79
  if (!options.suppressWarning) {
@@ -81,19 +83,17 @@ Subdocument.prototype.save = function(options, fn) {
81
83
  'if you\'re sure this behavior is right for your app.');
82
84
  }
83
85
 
84
- return promiseOrCallback(fn, cb => {
85
- this.$__save(cb);
86
- });
86
+ return await this.$__save(options);
87
87
  };
88
88
 
89
89
  /**
90
90
  * Given a path relative to this document, return the path relative
91
91
  * to the top-level document.
92
- * @param {String} path
92
+ * @param {string} path
93
93
  * @method $__fullPath
94
94
  * @memberOf Subdocument
95
95
  * @instance
96
- * @returns {String}
96
+ * @returns {string}
97
97
  * @api private
98
98
  */
99
99
 
@@ -109,9 +109,9 @@ Subdocument.prototype.$__fullPath = function(path) {
109
109
 
110
110
  /**
111
111
  * Given a path relative to this document, return the path relative
112
- * to the top-level document.
113
- * @param {String} p
114
- * @returns {String}
112
+ * to the parent document.
113
+ * @param {string} p
114
+ * @returns {string}
115
115
  * @method $__pathRelativeToParent
116
116
  * @memberOf Subdocument
117
117
  * @instance
@@ -122,6 +122,9 @@ Subdocument.prototype.$__pathRelativeToParent = function(p) {
122
122
  if (p == null) {
123
123
  return this.$basePath;
124
124
  }
125
+ if (!this.$basePath) {
126
+ return p;
127
+ }
125
128
  return [this.$basePath, p].join('.');
126
129
  };
127
130
 
@@ -137,8 +140,15 @@ Subdocument.prototype.$__pathRelativeToParent = function(p) {
137
140
  * @api private
138
141
  */
139
142
 
140
- Subdocument.prototype.$__save = function(fn) {
141
- return immediate(() => fn(null, this));
143
+ Subdocument.prototype.$__save = async function $__save(options) {
144
+ try {
145
+ await this._execDocumentPreHooks('save', options, [options]);
146
+ } catch (error) {
147
+ await this._execDocumentPostHooks('save', options, error);
148
+ return;
149
+ }
150
+
151
+ await this._execDocumentPostHooks('save', options);
142
152
  };
143
153
 
144
154
  /*!
@@ -167,8 +177,12 @@ Subdocument.prototype.markModified = function(path) {
167
177
  return;
168
178
  }
169
179
 
180
+ if (this.isNew) {
181
+ return;
182
+ }
183
+
170
184
  const myPath = this.$__pathRelativeToParent().replace(/\.$/, '');
171
- if (parent.isDirectModified(myPath) || this.isNew) {
185
+ if (parent.isDirectModified(myPath)) {
172
186
  return;
173
187
  }
174
188
  this.$__parent.markModified(fullPath, this);
@@ -197,7 +211,7 @@ Subdocument.prototype.isModified = function(paths, options, modifiedPaths) {
197
211
  /**
198
212
  * Marks a path as valid, removing existing validation errors.
199
213
  *
200
- * @param {String} path the field to mark as valid
214
+ * @param {string} path the field to mark as valid
201
215
  * @api private
202
216
  * @method $markValid
203
217
  * @memberOf Subdocument
@@ -254,7 +268,7 @@ Subdocument.prototype.ownerDocument = function() {
254
268
  return this.$__.ownerDocument;
255
269
  }
256
270
 
257
- let parent = this; // eslint-disable-line consistent-this
271
+ let parent = this;
258
272
  const paths = [];
259
273
  const seenDocs = new Set([parent]);
260
274
 
@@ -286,7 +300,7 @@ Subdocument.prototype.ownerDocument = function() {
286
300
  */
287
301
 
288
302
  Subdocument.prototype.$__fullPathWithIndexes = function() {
289
- let parent = this; // eslint-disable-line consistent-this
303
+ let parent = this;
290
304
  const paths = [];
291
305
  const seenDocs = new Set([parent]);
292
306
 
@@ -329,20 +343,14 @@ Subdocument.prototype.parent = function() {
329
343
 
330
344
  Subdocument.prototype.$parent = Subdocument.prototype.parent;
331
345
 
332
- /**
333
- * no-op for hooks
334
- * @param {Function} cb
335
- * @method $__remove
336
- * @memberOf Subdocument
337
- * @instance
346
+ /*!
347
+ * Sets this sub-documents parent document.
348
+ *
338
349
  * @api private
339
350
  */
340
351
 
341
- Subdocument.prototype.$__remove = function(cb) {
342
- if (cb == null) {
343
- return;
344
- }
345
- return cb(null, this);
352
+ Subdocument.prototype.$__setParent = function $__setParent(parent) {
353
+ this.$__parent = parent;
346
354
  };
347
355
 
348
356
  /**
@@ -360,23 +368,20 @@ Subdocument.prototype.$__removeFromParent = function() {
360
368
  /**
361
369
  * Null-out this subdoc
362
370
  *
363
- * @param {Object} [options]
364
- * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove
371
+ * @param {object} [options]
365
372
  */
366
373
 
367
- Subdocument.prototype.remove = function(options, callback) {
368
- if (typeof options === 'function') {
369
- callback = options;
370
- options = null;
371
- }
374
+ Subdocument.prototype.deleteOne = function deleteOne(options) {
372
375
  registerRemoveListener(this);
373
376
 
374
377
  // If removing entire doc, no need to remove subdoc
375
- if (!options || !options.noop) {
378
+ if (!options?.noop) {
376
379
  this.$__removeFromParent();
377
- }
378
380
 
379
- return this.$__remove(callback);
381
+ const owner = this.ownerDocument();
382
+ owner.$__.removedSubdocs = owner.$__.removedSubdocs || [];
383
+ owner.$__.removedSubdocs.push(this);
384
+ }
380
385
  };
381
386
 
382
387
  /*!
@@ -396,11 +401,7 @@ Subdocument.prototype.populate = function() {
396
401
  */
397
402
 
398
403
  Subdocument.prototype.inspect = function() {
399
- return this.toObject({
400
- transform: false,
401
- virtuals: false,
402
- flattenDecimals: false
403
- });
404
+ return this.toObject();
404
405
  };
405
406
 
406
407
  if (util.inspect.custom) {
@@ -408,6 +409,27 @@ if (util.inspect.custom) {
408
409
  Subdocument.prototype[util.inspect.custom] = Subdocument.prototype.inspect;
409
410
  }
410
411
 
412
+ /**
413
+ * Override `$toObject()` to handle minimizing the whole path. Should not minimize if schematype-level minimize
414
+ * is set to false re: gh-11247, gh-14058, gh-14151. Should not minimize document array elements: an array
415
+ * element cannot be removed without shifting the array, so minimizing it to `undefined` makes the BSON
416
+ * serializer store `null` re: gh-7322.
417
+ */
418
+
419
+ Subdocument.prototype.$toObject = function $toObject(options, json) {
420
+ const ret = Document.prototype.$toObject.call(this, options, json);
421
+
422
+ // If `$toObject()` was called recursively, respect the minimize option, including schematype level minimize.
423
+ // If minimize is set, then we can minimize out the whole object.
424
+ if (utils.hasOwnKeys(ret) === false && options?._calledWithOptions != null) {
425
+ const minimize = options._calledWithOptions?.minimize ?? this?.$__schemaTypeOptions?.minimize ?? options.minimize;
426
+ if (minimize && !this.constructor.$__required && !this.$isDocumentArrayElement) {
427
+ return undefined;
428
+ }
429
+ }
430
+ return ret;
431
+ };
432
+
411
433
  /**
412
434
  * Registers remove event listeners for triggering
413
435
  * on subdocuments.
@@ -417,16 +439,15 @@ if (util.inspect.custom) {
417
439
  */
418
440
 
419
441
  function registerRemoveListener(sub) {
420
- let owner = sub.ownerDocument();
442
+ const owner = sub.ownerDocument();
421
443
 
422
444
  function emitRemove() {
423
445
  owner.$removeListener('save', emitRemove);
424
- owner.$removeListener('remove', emitRemove);
425
- sub.emit('remove', sub);
426
- sub.constructor.emit('remove', sub);
427
- owner = sub = null;
446
+ owner.$removeListener('deleteOne', emitRemove);
447
+ sub.emit('deleteOne', sub);
448
+ sub.constructor.emit('deleteOne', sub);
428
449
  }
429
450
 
430
451
  owner.$on('save', emitRemove);
431
- owner.$on('remove', emitRemove);
452
+ owner.$on('deleteOne', emitRemove);
432
453
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * UUID type constructor
3
+ *
4
+ * #### Example:
5
+ *
6
+ * const id = new mongoose.Types.UUID();
7
+ *
8
+ * @constructor UUID
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ module.exports = require('mongodb/lib/bson').UUID;