@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
@@ -1,49 +1,42 @@
1
1
  'use strict';
2
- const modifiedPaths = require('./common').modifiedPaths;
3
2
  const get = require('./get');
4
3
 
5
4
  /**
6
5
  * Applies defaults to update and findOneAndUpdate operations.
7
6
  *
8
- * @param {Object} filter
7
+ * @param {object} filter
9
8
  * @param {Schema} schema
10
- * @param {Object} castedDoc
11
- * @param {Object} options
9
+ * @param {object} castedDoc
10
+ * @param {object} options
11
+ * @param {object} queryMongooseOptions
12
+ * @param {object | null} [context] the context to pass to default functions as `this`
12
13
  * @method setDefaultsOnInsert
13
14
  * @api private
14
15
  */
15
16
 
16
- module.exports = function(filter, schema, castedDoc, options) {
17
- options = options || {};
18
-
19
- const shouldSetDefaultsOnInsert =
20
- options.setDefaultsOnInsert != null ?
21
- options.setDefaultsOnInsert :
22
- schema.base.options.setDefaultsOnInsert;
17
+ module.exports = function(filter, schema, castedDoc, options, queryMongooseOptions, context) {
18
+ const shouldSetDefaultsOnInsert = options?.setDefaultsOnInsert ??
19
+ queryMongooseOptions?.setDefaultsOnInsert ??
20
+ schema.base.options.setDefaultsOnInsert;
23
21
 
24
22
  if (!options.upsert || shouldSetDefaultsOnInsert === false) {
25
23
  return castedDoc;
26
24
  }
27
25
 
28
26
  const keys = Object.keys(castedDoc || {});
29
- const updatedKeys = {};
27
+ const updatedKeys = Object.create(null);
30
28
  const updatedValues = {};
31
29
  const numKeys = keys.length;
32
- const modified = {};
33
30
 
34
31
  let hasDollarUpdate = false;
35
32
 
36
33
  for (let i = 0; i < numKeys; ++i) {
37
- if (keys[i].startsWith('$')) {
38
- modifiedPaths(castedDoc[keys[i]], '', modified);
34
+ if (keys[i].charAt(0) === '$') {
39
35
  hasDollarUpdate = true;
36
+ break;
40
37
  }
41
38
  }
42
39
 
43
- if (!hasDollarUpdate) {
44
- modifiedPaths(castedDoc, '', modified);
45
- }
46
-
47
40
  const paths = Object.keys(filter);
48
41
  const numPaths = paths.length;
49
42
  for (let i = 0; i < numPaths; ++i) {
@@ -54,7 +47,7 @@ module.exports = function(filter, schema, castedDoc, options) {
54
47
  const numConditionKeys = conditionKeys.length;
55
48
  let hasDollarKey = false;
56
49
  for (let j = 0; j < numConditionKeys; ++j) {
57
- if (conditionKeys[j].startsWith('$')) {
50
+ if (conditionKeys[j].charAt(0) === '$') {
58
51
  hasDollarKey = true;
59
52
  break;
60
53
  }
@@ -64,10 +57,23 @@ module.exports = function(filter, schema, castedDoc, options) {
64
57
  }
65
58
  }
66
59
  updatedKeys[path] = true;
67
- modified[path] = true;
60
+ if (path.indexOf('.') === -1) {
61
+ continue;
62
+ }
63
+ // Also mark all parent prefixes so child-path lookups are O(1).
64
+ // e.g. 'extraProps.location' also marks 'extraProps'
65
+ const pieces = schema.paths[path] ?
66
+ // If the SchemaType already split for us, use that to avoid the extra overhead
67
+ schema.paths[path].splitPath() :
68
+ path.split('.');
69
+ let cur = pieces[0];
70
+ for (let j = 1; j < pieces.length; ++j) {
71
+ updatedKeys[cur] = true;
72
+ cur += '.' + pieces[j];
73
+ }
68
74
  }
69
75
 
70
- if (options && options.overwrite && !hasDollarUpdate) {
76
+ if (options?.overwrite && !hasDollarUpdate) {
71
77
  // Defaults will be set later, since we're overwriting we'll cast
72
78
  // the whole update to a document
73
79
  return castedDoc;
@@ -78,17 +84,18 @@ module.exports = function(filter, schema, castedDoc, options) {
78
84
  if (schemaType.path === '_id' && schemaType.options.auto) {
79
85
  return;
80
86
  }
81
- const def = schemaType.getDefault(null, true);
82
- if (isModified(modified, path)) {
83
- return;
84
- }
87
+ const def = schemaType.getDefault(null, true, { context });
85
88
  if (typeof def === 'undefined') {
86
89
  return;
87
90
  }
88
- if (schemaType.splitPath().includes('$*')) {
91
+ const pathPieces = schemaType.splitPath();
92
+ if (pathPieces.includes('$*')) {
89
93
  // Skip defaults underneath maps. We should never do `$setOnInsert` on a path with `$*`
90
94
  return;
91
95
  }
96
+ if (isModified(castedDoc, updatedKeys, path, pathPieces, hasDollarUpdate)) {
97
+ return;
98
+ }
92
99
 
93
100
  castedDoc = castedDoc || {};
94
101
  castedDoc.$setOnInsert = castedDoc.$setOnInsert || {};
@@ -101,31 +108,66 @@ module.exports = function(filter, schema, castedDoc, options) {
101
108
  return castedDoc;
102
109
  };
103
110
 
104
- function isModified(modified, path) {
105
- if (modified[path]) {
111
+ function isModified(castedDoc, updatedKeys, path, pathPieces, hasDollarUpdate) {
112
+ // Check if path is in filter (updatedKeys)
113
+ if (updatedKeys[path]) {
106
114
  return true;
107
115
  }
108
116
 
109
- // Is any parent path of `path` modified?
110
- const sp = path.split('.');
111
- let cur = sp[0];
112
- for (let i = 1; i < sp.length; ++i) {
113
- if (modified[cur]) {
117
+ // Check if any parent path is in filter
118
+ let cur = pathPieces[0];
119
+ for (let i = 1; i < pathPieces.length; ++i) {
120
+ if (updatedKeys[cur]) {
114
121
  return true;
115
122
  }
116
- cur += '.' + sp[i];
123
+ cur += '.' + pathPieces[i];
117
124
  }
118
125
 
119
- // Is any child of `path` modified?
120
- const modifiedKeys = Object.keys(modified);
121
- if (modifiedKeys.length) {
122
- const parentPath = path + '.';
123
-
124
- for (const modifiedPath of modifiedKeys) {
125
- if (modifiedPath.slice(0, path.length + 1) === parentPath) {
126
- return true;
126
+ // Check if path is modified in the update
127
+ if (hasDollarUpdate) {
128
+ // Check each update operator
129
+ for (const key in castedDoc) {
130
+ if (key.charAt(0) === '$') {
131
+ if (pathExistsInUpdate(castedDoc[key], path, pathPieces)) {
132
+ return true;
133
+ }
127
134
  }
128
135
  }
136
+ } else {
137
+ // No dollar operators, check the castedDoc directly
138
+ if (pathExistsInUpdate(castedDoc, path, pathPieces)) {
139
+ return true;
140
+ }
141
+ }
142
+
143
+ return false;
144
+ }
145
+
146
+ function pathExistsInUpdate(update, targetPath, pathPieces) {
147
+ if (update == null || typeof update !== 'object') {
148
+ return false;
149
+ }
150
+
151
+ // Check exact match
152
+ if (Object.hasOwn(update, targetPath)) {
153
+ return true;
154
+ }
155
+
156
+ // Check if any parent path exists
157
+ let cur = pathPieces[0];
158
+ for (let i = 1; i < pathPieces.length; ++i) {
159
+ if (Object.hasOwn(update, cur)) {
160
+ return true;
161
+ }
162
+ cur += '.' + pathPieces[i];
163
+ }
164
+
165
+ // Check if any child path exists (e.g., path is "a" and update has "a.b")
166
+ const prefix = targetPath + '.';
167
+ for (const key in update) {
168
+ if (key.startsWith(prefix)) {
169
+ return true;
170
+ }
129
171
  }
130
172
 
131
173
  return false;
@@ -5,7 +5,7 @@ exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics');
5
5
  exports.arrayParentSymbol = Symbol('mongoose#Array#_parent');
6
6
  exports.arrayPathSymbol = Symbol('mongoose#Array#_path');
7
7
  exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema');
8
- exports.documentArrayParent = Symbol('mongoose:documentArrayParent');
8
+ exports.documentArrayParent = Symbol('mongoose#documentArrayParent');
9
9
  exports.documentIsSelected = Symbol('mongoose#Document#isSelected');
10
10
  exports.documentIsModified = Symbol('mongoose#Document#isModified');
11
11
  exports.documentModifiedPaths = Symbol('mongoose#Document#modifiedPaths');
@@ -13,8 +13,8 @@ exports.documentSchemaSymbol = Symbol('mongoose#Document#schema');
13
13
  exports.getSymbol = Symbol('mongoose#Document#get');
14
14
  exports.modelSymbol = Symbol('mongoose#Model');
15
15
  exports.objectIdSymbol = Symbol('mongoose#ObjectId');
16
- exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model');
16
+ exports.populateModelSymbol = Symbol('mongoose#PopulateOptions#Model');
17
17
  exports.schemaTypeSymbol = Symbol('mongoose#schemaType');
18
- exports.sessionNewDocuments = Symbol('mongoose:ClientSession#newDocuments');
18
+ exports.sessionNewDocuments = Symbol('mongoose#ClientSession#newDocuments');
19
19
  exports.scopeSymbol = Symbol('mongoose#Document#scope');
20
- exports.validatorErrorSymbol = Symbol('mongoose:validatorError');
20
+ exports.validatorErrorSymbol = Symbol('mongoose#validatorError');
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  module.exports = function setDocumentTimestamps(doc, timestampOption, currentTime, createdAt, updatedAt) {
4
- const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false;
5
- const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false;
4
+ const skipUpdatedAt = timestampOption?.updatedAt === false;
5
+ const skipCreatedAt = timestampOption?.createdAt === false;
6
6
 
7
7
  const defaultTimestamp = currentTime != null ?
8
8
  currentTime() :
@@ -2,25 +2,27 @@
2
2
 
3
3
  const applyTimestampsToChildren = require('../update/applyTimestampsToChildren');
4
4
  const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate');
5
- const get = require('../get');
6
5
  const handleTimestampOption = require('../schema/handleTimestampOption');
7
6
  const setDocumentTimestamps = require('./setDocumentTimestamps');
8
7
  const symbols = require('../../schema/symbols');
9
8
 
9
+ const replaceOps = new Set([
10
+ 'replaceOne',
11
+ 'findOneAndReplace'
12
+ ]);
13
+
10
14
  module.exports = function setupTimestamps(schema, timestamps) {
11
15
  const childHasTimestamp = schema.childSchemas.find(withTimestamp);
12
16
  function withTimestamp(s) {
13
17
  const ts = s.schema.options.timestamps;
14
18
  return !!ts;
15
19
  }
16
-
17
20
  if (!timestamps && !childHasTimestamp) {
18
21
  return;
19
22
  }
20
-
21
23
  const createdAt = handleTimestampOption(timestamps, 'createdAt');
22
24
  const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
23
- const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ?
25
+ const currentTime = timestamps != null && Object.hasOwn(timestamps, 'currentTime') ?
24
26
  timestamps.currentTime :
25
27
  null;
26
28
  const schemaAdditions = {};
@@ -28,8 +30,8 @@ module.exports = function setupTimestamps(schema, timestamps) {
28
30
  schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
29
31
 
30
32
  if (createdAt && !schema.paths[createdAt]) {
31
- const baseImmutableCreatedAt = schema.base != null ? schema.base.get('timestamps.createdAt.immutable') : null;
32
- const immutable = baseImmutableCreatedAt != null ? baseImmutableCreatedAt : true;
33
+ const baseImmutableCreatedAt = schema.base?.get('timestamps.createdAt.immutable') ?? null;
34
+ const immutable = baseImmutableCreatedAt ?? true;
33
35
  schemaAdditions[createdAt] = { [schema.options.typeKey || 'type']: Date, immutable };
34
36
  }
35
37
 
@@ -39,28 +41,28 @@ module.exports = function setupTimestamps(schema, timestamps) {
39
41
 
40
42
  schema.add(schemaAdditions);
41
43
 
42
- schema.pre('save', function timestampsPreSave(next) {
43
- const timestampOption = get(this, '$__.saveOptions.timestamps');
44
- if (timestampOption === false) {
45
- return next();
46
- }
44
+ schema.pre('save', timestampsPreSave);
47
45
 
48
- setDocumentTimestamps(this, timestampOption, currentTime, createdAt, updatedAt);
46
+ schema.methods.initializeTimestamps = function(timestampsOptions) {
47
+ if (timestampsOptions === false) {
48
+ return this;
49
+ }
50
+ const ts = currentTime != null ?
51
+ currentTime() : this.constructor.base.now();
49
52
 
50
- next();
51
- });
53
+ const initTimestampsCreatedAt = timestampsOptions != null ?
54
+ handleTimestampOption(timestampsOptions, 'createdAt') :
55
+ createdAt;
56
+ const initTimestampsUpdatedAt = timestampsOptions != null ?
57
+ handleTimestampOption(timestampsOptions, 'updatedAt') :
58
+ updatedAt;
52
59
 
53
- schema.methods.initializeTimestamps = function() {
54
- const ts = currentTime != null ?
55
- currentTime() :
56
- this.constructor.base.now();
57
- if (createdAt && !this.get(createdAt)) {
60
+ if (initTimestampsCreatedAt && !this.get(initTimestampsCreatedAt)) {
58
61
  this.$set(createdAt, ts);
59
62
  }
60
- if (updatedAt && !this.get(updatedAt)) {
63
+ if (initTimestampsUpdatedAt && !this.get(initTimestampsUpdatedAt)) {
61
64
  this.$set(updatedAt, ts);
62
65
  }
63
-
64
66
  if (this.$isSubdocument) {
65
67
  return this;
66
68
  }
@@ -68,15 +70,13 @@ module.exports = function setupTimestamps(schema, timestamps) {
68
70
  const subdocs = this.$getAllSubdocs();
69
71
  for (const subdoc of subdocs) {
70
72
  if (subdoc.initializeTimestamps) {
71
- subdoc.initializeTimestamps();
73
+ subdoc.initializeTimestamps(timestampsOptions);
72
74
  }
73
75
  }
74
76
 
75
77
  return this;
76
78
  };
77
79
 
78
- _setTimestampsOnUpdate[symbols.builtInMiddleware] = true;
79
-
80
80
  const opts = { query: true, model: false };
81
81
  schema.pre('findOneAndReplace', opts, _setTimestampsOnUpdate);
82
82
  schema.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate);
@@ -84,18 +84,50 @@ module.exports = function setupTimestamps(schema, timestamps) {
84
84
  schema.pre('update', opts, _setTimestampsOnUpdate);
85
85
  schema.pre('updateOne', opts, _setTimestampsOnUpdate);
86
86
  schema.pre('updateMany', opts, _setTimestampsOnUpdate);
87
+ };
87
88
 
88
- function _setTimestampsOnUpdate(next) {
89
- const now = currentTime != null ?
90
- currentTime() :
91
- this.model.base.now();
92
- // Replacing with null update should still trigger timestamps
93
- if (this.op === 'findOneAndReplace' && this.getUpdate() == null) {
94
- this.setUpdate({});
95
- }
96
- applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(),
97
- this.options, this.schema);
98
- applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
99
- next();
89
+ function timestampsPreSave() {
90
+ const timestampOption = this.$__?.saveOptions?.timestamps;
91
+ if (timestampOption === false) {
92
+ return;
100
93
  }
101
- };
94
+
95
+ const schema = this.$__schema;
96
+ const { createdAt, updatedAt } = schema.$timestamps;
97
+ const timestamps = schema.options.timestamps;
98
+ const currentTime = timestamps != null && Object.hasOwn(timestamps, 'currentTime') ?
99
+ timestamps.currentTime :
100
+ null;
101
+
102
+ setDocumentTimestamps(this, timestampOption, currentTime, createdAt, updatedAt);
103
+ }
104
+
105
+ function _setTimestampsOnUpdate() {
106
+ const schema = this.model.schema;
107
+ const { createdAt, updatedAt } = schema.$timestamps;
108
+ const timestamps = schema.options.timestamps;
109
+ const currentTime = timestamps != null && Object.hasOwn(timestamps, 'currentTime') ?
110
+ timestamps.currentTime :
111
+ null;
112
+
113
+ const now = currentTime != null ?
114
+ currentTime() :
115
+ this.model.base.now();
116
+ // Replacing with null update should still trigger timestamps
117
+ if (replaceOps.has(this.op) && this.getUpdate() == null) {
118
+ this.setUpdate({});
119
+ }
120
+ applyTimestampsToUpdate(
121
+ now,
122
+ createdAt,
123
+ updatedAt,
124
+ this.getUpdate(),
125
+ this._mongooseOptions,
126
+ this.options.upsert,
127
+ replaceOps.has(this.op)
128
+ );
129
+ applyTimestampsToChildren(now, this.getUpdate(), this.model.schema);
130
+ }
131
+
132
+ timestampsPreSave[symbols.builtInMiddleware] = true;
133
+ _setTimestampsOnUpdate[symbols.builtInMiddleware] = true;
@@ -45,7 +45,7 @@ function applyTimestampsToChildren(now, update, schema) {
45
45
 
46
46
  function _applyTimestampToUpdateOperator(op) {
47
47
  for (const key of Object.keys(op)) {
48
- const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, ''));
48
+ const $path = schema.path(cleanPositionalOperators(key));
49
49
  if (op[key] &&
50
50
  $path &&
51
51
  $path.$isMongooseDocumentArray &&
@@ -4,6 +4,7 @@
4
4
  * ignore
5
5
  */
6
6
 
7
+ const utils = require('../../utils');
7
8
  const get = require('../get');
8
9
 
9
10
  module.exports = applyTimestampsToUpdate;
@@ -12,22 +13,21 @@ module.exports = applyTimestampsToUpdate;
12
13
  * ignore
13
14
  */
14
15
 
15
- function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) {
16
+ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options, upsert, isReplace) {
16
17
  const updates = currentUpdate;
17
18
  let _updates = updates;
18
- const overwrite = get(options, 'overwrite', false);
19
- const timestamps = get(options, 'timestamps', true);
19
+ const timestamps = options?.timestamps ?? true;
20
20
 
21
21
  // Support skipping timestamps at the query level, see gh-6980
22
22
  if (!timestamps || updates == null) {
23
23
  return currentUpdate;
24
24
  }
25
25
 
26
- const skipCreatedAt = timestamps != null && timestamps.createdAt === false;
27
- const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false;
26
+ const skipCreatedAt = timestamps?.createdAt === false;
27
+ const skipUpdatedAt = timestamps?.updatedAt === false;
28
28
 
29
- if (overwrite) {
30
- if (currentUpdate && currentUpdate.$set) {
29
+ if (isReplace) {
30
+ if (currentUpdate?.$set) {
31
31
  currentUpdate = currentUpdate.$set;
32
32
  updates.$set = {};
33
33
  _updates = updates.$set;
@@ -44,14 +44,15 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio
44
44
 
45
45
  if (Array.isArray(updates)) {
46
46
  // Update with aggregation pipeline
47
+ if (updatedAt == null || skipUpdatedAt) {
48
+ return updates;
49
+ }
47
50
  updates.push({ $set: { [updatedAt]: now } });
48
-
49
51
  return updates;
50
52
  }
51
-
52
53
  updates.$set = updates.$set || {};
53
54
  if (!skipUpdatedAt && updatedAt &&
54
- (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) {
55
+ !currentUpdate.$currentDate?.[updatedAt]) {
55
56
  let timestampSet = false;
56
57
  if (updatedAt.indexOf('.') !== -1) {
57
58
  const pieces = updatedAt.split('.');
@@ -62,7 +63,7 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio
62
63
  currentUpdate[start][remnant] = now;
63
64
  timestampSet = true;
64
65
  break;
65
- } else if (currentUpdate.$set && currentUpdate.$set[start]) {
66
+ } else if (currentUpdate.$set?.[start]) {
66
67
  currentUpdate.$set[start][remnant] = now;
67
68
  timestampSet = true;
68
69
  break;
@@ -74,43 +75,58 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio
74
75
  updates.$set[updatedAt] = now;
75
76
  }
76
77
 
77
- if (updates.hasOwnProperty(updatedAt)) {
78
+ if (Object.hasOwn(updates, updatedAt)) {
78
79
  delete updates[updatedAt];
79
80
  }
80
81
  }
81
82
 
82
83
  if (!skipCreatedAt && createdAt) {
83
- if (currentUpdate[createdAt]) {
84
- delete currentUpdate[createdAt];
85
- }
86
- if (currentUpdate.$set && currentUpdate.$set[createdAt]) {
87
- delete currentUpdate.$set[createdAt];
88
- }
89
- let timestampSet = false;
90
- if (createdAt.indexOf('.') !== -1) {
91
- const pieces = createdAt.split('.');
92
- for (let i = 1; i < pieces.length; ++i) {
93
- const remnant = pieces.slice(-i).join('.');
94
- const start = pieces.slice(0, -i).join('.');
95
- if (currentUpdate[start] != null) {
96
- currentUpdate[start][remnant] = now;
97
- timestampSet = true;
98
- break;
99
- } else if (currentUpdate.$set && currentUpdate.$set[start]) {
100
- currentUpdate.$set[start][remnant] = now;
101
- timestampSet = true;
102
- break;
84
+ const overwriteImmutable = options?.overwriteImmutable;
85
+ const hasUserCreatedAt = get(currentUpdate, createdAt) != null
86
+ || get(currentUpdate.$set, createdAt) != null
87
+ || get(currentUpdate.$setOnInsert, createdAt) != null;
88
+
89
+ // If overwriteImmutable is true and user provided createdAt, keep their value
90
+ if (overwriteImmutable && hasUserCreatedAt) {
91
+ // Move createdAt from top-level to $set if needed
92
+ if (currentUpdate[createdAt] != null) {
93
+ updates.$set[createdAt] = currentUpdate[createdAt];
94
+ delete currentUpdate[createdAt];
95
+ }
96
+ // User's value is already in $set or $setOnInsert, nothing more to do
97
+ } else {
98
+ if (currentUpdate[createdAt]) {
99
+ delete currentUpdate[createdAt];
100
+ }
101
+ if (currentUpdate.$set?.[createdAt]) {
102
+ delete currentUpdate.$set[createdAt];
103
+ }
104
+ let timestampSet = false;
105
+ if (createdAt.indexOf('.') !== -1) {
106
+ const pieces = createdAt.split('.');
107
+ for (let i = 1; i < pieces.length; ++i) {
108
+ const remnant = pieces.slice(-i).join('.');
109
+ const start = pieces.slice(0, -i).join('.');
110
+ if (currentUpdate[start] != null) {
111
+ currentUpdate[start][remnant] = now;
112
+ timestampSet = true;
113
+ break;
114
+ } else if (currentUpdate.$set?.[start]) {
115
+ currentUpdate.$set[start][remnant] = now;
116
+ timestampSet = true;
117
+ break;
118
+ }
103
119
  }
104
120
  }
105
- }
106
121
 
107
- if (!timestampSet) {
108
- updates.$setOnInsert = updates.$setOnInsert || {};
109
- updates.$setOnInsert[createdAt] = now;
122
+ if (!timestampSet && upsert) {
123
+ updates.$setOnInsert = updates.$setOnInsert || {};
124
+ updates.$setOnInsert[createdAt] = now;
125
+ }
110
126
  }
111
127
  }
112
128
 
113
- if (Object.keys(updates.$set).length === 0) {
129
+ if (utils.hasOwnKeys(updates.$set) === false) {
114
130
  delete updates.$set;
115
131
  }
116
132
  return updates;