@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
@@ -2,28 +2,52 @@
2
2
 
3
3
  const CastError = require('../../error/cast');
4
4
  const MongooseError = require('../../error/mongooseError');
5
+ const SchemaString = require('../../schema/string');
5
6
  const StrictModeError = require('../../error/strict');
6
7
  const ValidationError = require('../../error/validation');
7
8
  const castNumber = require('../../cast/number');
8
9
  const cast = require('../../cast');
9
10
  const getConstructorName = require('../getConstructorName');
11
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
12
+ const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
10
13
  const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
14
+ const getOwnProperty = require('../getOwnProperty');
11
15
  const handleImmutable = require('./handleImmutable');
16
+ const isMongooseDocument = require('../isMongooseDocument');
17
+ const isOperator = require('./isOperator');
12
18
  const moveImmutableProperties = require('../update/moveImmutableProperties');
13
19
  const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
14
20
  const setDottedPath = require('../path/setDottedPath');
15
21
  const utils = require('../../utils');
22
+ const { internalToObjectOptions } = require('../../options');
23
+
24
+ const mongodbUpdateOperators = new Set([
25
+ '$currentDate',
26
+ '$inc',
27
+ '$min',
28
+ '$max',
29
+ '$mul',
30
+ '$rename',
31
+ '$set',
32
+ '$setOnInsert',
33
+ '$unset',
34
+ '$addToSet',
35
+ '$pop',
36
+ '$pull',
37
+ '$push',
38
+ '$pullAll',
39
+ '$bit'
40
+ ]);
16
41
 
17
42
  /**
18
43
  * Casts an update op based on the given schema
19
44
  *
20
45
  * @param {Schema} schema
21
- * @param {Object} obj
22
- * @param {Object} [options]
23
- * @param {Boolean} [options.overwrite] defaults to false
24
- * @param {Boolean|String} [options.strict] defaults to true
46
+ * @param {object} obj
47
+ * @param {object} [options]
48
+ * @param {boolean|'throw'} [options.strict] defaults to true
25
49
  * @param {Query} context passed to setters
26
- * @return {Boolean} true iff the update is non-empty
50
+ * @return {boolean} true iff the update is non-empty
27
51
  * @api private
28
52
  */
29
53
  module.exports = function castUpdate(schema, obj, options, context, filter) {
@@ -43,22 +67,55 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
43
67
  return obj;
44
68
  }
45
69
 
46
- if (options.upsert && !options.overwrite) {
70
+ if (schema != null &&
71
+ filter != null &&
72
+ utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) &&
73
+ typeof filter[schema.options.discriminatorKey] !== 'object' &&
74
+ schema.discriminators != null) {
75
+ const discriminatorValue = filter[schema.options.discriminatorKey];
76
+ const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
77
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
78
+ byValue?.schema ||
79
+ schema;
80
+ } else if (schema != null &&
81
+ options.overwriteDiscriminatorKey &&
82
+ utils.hasUserDefinedProperty(obj, schema.options.discriminatorKey) &&
83
+ schema.discriminators != null) {
84
+ const discriminatorValue = obj[schema.options.discriminatorKey];
85
+ const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
86
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
87
+ byValue?.schema ||
88
+ schema;
89
+ } else if (schema != null &&
90
+ options.overwriteDiscriminatorKey &&
91
+ obj.$set != null &&
92
+ utils.hasUserDefinedProperty(obj.$set, schema.options.discriminatorKey) &&
93
+ schema.discriminators != null) {
94
+ const discriminatorValue = obj.$set[schema.options.discriminatorKey];
95
+ const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
96
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
97
+ byValue?.schema ||
98
+ schema;
99
+ }
100
+
101
+ if (options.upsert && !options.overwriteImmutable) {
47
102
  moveImmutableProperties(schema, obj, context);
48
103
  }
49
104
 
105
+ if (isMongooseDocument(obj) && typeof obj.toObject === 'function') {
106
+ obj = obj.toObject(internalToObjectOptions);
107
+ }
108
+
50
109
  const ops = Object.keys(obj);
51
110
  let i = ops.length;
52
111
  const ret = {};
53
112
  let val;
54
113
  let hasDollarKey = false;
55
- const overwrite = options.overwrite;
56
114
 
57
115
  filter = filter || {};
58
116
  while (i--) {
59
117
  const op = ops[i];
60
- // if overwrite is set, don't do any of the special $set stuff
61
- if (op[0] !== '$' && !overwrite) {
118
+ if (!mongodbUpdateOperators.has(op)) {
62
119
  // fix up $set sugar
63
120
  if (!ret.$set) {
64
121
  if (obj.$set) {
@@ -84,14 +141,15 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
84
141
  const op = ops[i];
85
142
  val = ret[op];
86
143
  hasDollarKey = hasDollarKey || op.startsWith('$');
87
-
144
+ if (isMongooseDocument(val)) {
145
+ val = val.toObject(internalToObjectOptions);
146
+ ret[op] = val;
147
+ }
88
148
  if (val &&
89
149
  typeof val === 'object' &&
90
150
  !Buffer.isBuffer(val) &&
91
- (!overwrite || hasDollarKey)) {
151
+ mongodbUpdateOperators.has(op)) {
92
152
  walkUpdatePath(schema, val, op, options, context, filter);
93
- } else if (overwrite && ret && typeof ret === 'object') {
94
- walkUpdatePath(schema, ret, '$set', options, context, filter);
95
153
  } else {
96
154
  const msg = 'Invalid atomic update value for ' + op + '. '
97
155
  + 'Expected an object, received ' + typeof val;
@@ -103,12 +161,13 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
103
161
  }
104
162
  }
105
163
 
106
- if (Object.keys(ret).length === 0 &&
164
+ if (utils.hasOwnKeys(ret) === false &&
107
165
  options.upsert &&
108
- Object.keys(filter).length > 0) {
166
+ utils.hasOwnKeys(filter)) {
109
167
  // Trick the driver into allowing empty upserts to work around
110
168
  // https://github.com/mongodb/node-mongodb-native/pull/2490
111
- return { $setOnInsert: filter };
169
+ // Shallow clone to avoid passing defaults in re: gh-13962
170
+ return { $setOnInsert: { ...filter } };
112
171
  }
113
172
  return ret;
114
173
  };
@@ -151,20 +210,20 @@ function castPipelineOperator(op, val) {
151
210
  * according to its schema.
152
211
  *
153
212
  * @param {Schema} schema
154
- * @param {Object} obj part of a query
155
- * @param {String} op the atomic operator ($pull, $set, etc)
156
- * @param {Object} [options]
157
- * @param {Boolean|String} [options.strict]
213
+ * @param {object} obj part of a query
214
+ * @param {string} op the atomic operator ($pull, $set, etc)
215
+ * @param {object} [options]
216
+ * @param {boolean|'throw'} [options.strict]
158
217
  * @param {Query} context
159
- * @param {Object} filter
160
- * @param {String} pref path prefix (internal only)
218
+ * @param {object} filter
219
+ * @param {string} pref path prefix (internal only)
161
220
  * @return {Bool} true if this path has keys to update
162
221
  * @api private
163
222
  */
164
223
 
165
- function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
224
+ function walkUpdatePath(schema, obj, op, options, context, filter, prefix) {
166
225
  const strict = options.strict;
167
- const prefix = pref ? pref + '.' : '';
226
+ prefix = prefix ? prefix + '.' : '';
168
227
  const keys = Object.keys(obj);
169
228
  let i = keys.length;
170
229
  let hasKeys = false;
@@ -174,18 +233,48 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
174
233
 
175
234
  let aggregatedError = null;
176
235
 
177
- const strictMode = strict != null ? strict : schema.options.strict;
236
+ const strictMode = strict ?? schema.options.strict;
178
237
 
179
238
  while (i--) {
180
239
  key = keys[i];
181
240
  val = obj[key];
182
241
 
242
+ const fullPath = prefix + key;
243
+ const isTopLevelOperator = !prefix && isOperator(key);
244
+ let fullPathSchema = isTopLevelOperator ? schema._getSchema(fullPath) : null;
245
+ const isTopLevelNestedDollarPath = isTopLevelOperator && Object.hasOwn(schema.nested, key);
246
+ if (isTopLevelOperator &&
247
+ fullPathSchema == null &&
248
+ !isTopLevelNestedDollarPath) {
249
+ throw new MongooseError('Invalid update: Unexpected modifier "' + key + '" as a key in operator "' + op + '". '
250
+ + 'Did you mean something like { ' + op + ': { fieldName: { ' + key + ': [...] } } }? '
251
+ + 'Modifiers must appear under a valid field path.');
252
+ }
253
+
183
254
  // `$pull` is special because we need to cast the RHS as a query, not as
184
255
  // an update.
185
256
  if (op === '$pull') {
186
- schematype = schema._getSchema(prefix + key);
187
- if (schematype != null && schematype.schema != null) {
188
- obj[key] = cast(schematype.schema, obj[key], options, context);
257
+ if (!isTopLevelOperator) {
258
+ fullPathSchema = schema._getSchema(fullPath);
259
+ }
260
+ schematype = fullPathSchema;
261
+ if (schematype == null) {
262
+ const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options);
263
+ if (_res.schematype != null) {
264
+ schematype = _res.schematype;
265
+ }
266
+ }
267
+ if (schematype?.schema != null) {
268
+ try {
269
+ obj[key] = cast(schematype.schema, obj[key], options, context);
270
+ } catch (error) {
271
+ if (error instanceof CastError) {
272
+ aggregatedError = _appendError(error, context, key, aggregatedError);
273
+ continue;
274
+ } else {
275
+ throw error;
276
+ }
277
+ }
189
278
  hasKeys = true;
190
279
  continue;
191
280
  }
@@ -208,10 +297,13 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
208
297
  }
209
298
  }
210
299
 
300
+ if (!isTopLevelOperator && op !== '$pull') {
301
+ fullPathSchema = schema._getSchema(fullPath);
302
+ }
303
+ schematype = fullPathSchema;
304
+
211
305
  if (getConstructorName(val) === 'Object') {
212
306
  // watch for embedded doc schemas
213
- schematype = schema._getSchema(prefix + key);
214
-
215
307
  if (schematype == null) {
216
308
  const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, prefix + key, options);
217
309
  if (_res.schematype != null) {
@@ -220,12 +312,11 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
220
312
  }
221
313
 
222
314
  if (op !== '$setOnInsert' &&
223
- !options.overwrite &&
224
- handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
315
+ handleImmutable(schematype, strict, obj, key, prefix + key, options, context)) {
225
316
  continue;
226
317
  }
227
318
 
228
- if (schematype && schematype.caster && op in castOps) {
319
+ if (schematype && (schematype.embeddedSchemaType || schematype.Constructor) && op in castOps) {
229
320
  // embedded doc schema
230
321
  if ('$each' in val) {
231
322
  hasKeys = true;
@@ -249,10 +340,10 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
249
340
  obj[key].$position = castNumber(val.$position);
250
341
  }
251
342
  } else {
252
- if (schematype != null && schematype.$isSingleNested) {
343
+ if (schematype?.$isSingleNested) {
253
344
  const _strict = strict == null ? schematype.schema.options.strict : strict;
254
345
  try {
255
- obj[key] = schematype.castForQuery(val, context, { strict: _strict });
346
+ obj[key] = schematype.castForQuery(null, val, context, { strict: _strict });
256
347
  } catch (error) {
257
348
  aggregatedError = _appendError(error, context, key, aggregatedError);
258
349
  }
@@ -284,12 +375,26 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
284
375
  continue;
285
376
  }
286
377
 
378
+ hasKeys = true;
379
+ } else if (op === '$rename') {
380
+ const schematype = new SchemaString(`${prefix}${key}.$rename`);
381
+ try {
382
+ obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
383
+ } catch (error) {
384
+ aggregatedError = _appendError(error, context, key, aggregatedError);
385
+ }
386
+
387
+ if (obj[key] === void 0) {
388
+ delete obj[key];
389
+ continue;
390
+ }
391
+
287
392
  hasKeys = true;
288
393
  } else {
289
394
  const pathToCheck = (prefix + key);
290
395
  const v = schema._getPathType(pathToCheck);
291
396
  let _strict = strict;
292
- if (v && v.schema && _strict == null) {
397
+ if (v?.schema && _strict == null) {
293
398
  _strict = v.schema.options.strict;
294
399
  }
295
400
 
@@ -306,17 +411,19 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
306
411
  // we should be able to set a schema-less field
307
412
  // to an empty object literal
308
413
  hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) ||
309
- (utils.isObject(val) && Object.keys(val).length === 0);
414
+ (utils.isObject(val) && utils.hasOwnKeys(val) === false);
310
415
  }
311
416
  } else {
312
- const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ?
313
- pref : prefix + key;
314
- schematype = schema._getSchema(checkPath);
417
+ const isModifier = !isTopLevelNestedDollarPath && schematype == null &&
418
+ (key === '$each' || key === '$or' || key === '$and' || key === '$in');
419
+ const checkPath = isModifier ? prefix : fullPath;
420
+ if (isModifier) {
421
+ schematype = schema._getSchema(checkPath);
422
+ }
315
423
 
316
424
  // You can use `$setOnInsert` with immutable keys
317
425
  if (op !== '$setOnInsert' &&
318
- !options.overwrite &&
319
- handleImmutable(schematype, strict, obj, key, prefix + key, context)) {
426
+ handleImmutable(schematype, strict, obj, key, prefix + key, options, context)) {
320
427
  continue;
321
428
  }
322
429
 
@@ -333,7 +440,7 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
333
440
  }
334
441
 
335
442
  let isStrict = strict;
336
- if (pathDetails && pathDetails.schema && strict == null) {
443
+ if (pathDetails?.schema && strict == null) {
337
444
  isStrict = pathDetails.schema.options.strict;
338
445
  }
339
446
 
@@ -344,23 +451,29 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
344
451
  if (skip) {
345
452
  // Even if strict is `throw`, avoid throwing an error because of
346
453
  // virtuals because of #6731
347
- if (isStrict === 'throw' && schema.virtuals[checkPath] == null) {
454
+ if (isStrict === 'throw' && getOwnProperty(schema.virtuals, checkPath) == null) {
348
455
  throw new StrictModeError(prefix + key);
349
456
  } else {
350
457
  delete obj[key];
351
458
  }
352
459
  } else {
353
- // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking
354
- // improving this.
355
460
  if (op === '$rename') {
356
- hasKeys = true;
461
+ try {
462
+ if (obj[key] == null) {
463
+ throw new CastError('String', obj[key], `${prefix}${key}.$rename`);
464
+ }
465
+ const schematype = new SchemaString(`${prefix}${key}.$rename`, null, null, schema);
466
+ obj[key] = schematype.castForQuery(null, obj[key], context);
467
+ } catch (error) {
468
+ aggregatedError = _appendError(error, context, key, aggregatedError);
469
+ }
357
470
  continue;
358
471
  }
359
472
 
360
473
  try {
361
474
  if (prefix.length === 0 || key.indexOf('.') === -1) {
362
475
  obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key);
363
- } else {
476
+ } else if (isStrict !== false || schematype != null) {
364
477
  // Setting a nested dotted path that's in the schema. We don't allow paths with '.' in
365
478
  // a schema, so replace the dotted path with a nested object to avoid ending up with
366
479
  // dotted properties in the updated object. See (gh-10200)
@@ -373,9 +486,9 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
373
486
 
374
487
  if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') {
375
488
  if (schematype &&
376
- schematype.caster &&
377
- !schematype.caster.$isMongooseArray &&
378
- !schematype.caster[schemaMixedSymbol]) {
489
+ schematype.embeddedSchemaType &&
490
+ !schematype.embeddedSchemaType.$isMongooseArray &&
491
+ !schematype.embeddedSchemaType[schemaMixedSymbol]) {
379
492
  obj[key] = { $each: obj[key] };
380
493
  }
381
494
  }
@@ -402,6 +515,14 @@ function walkUpdatePath(schema, obj, op, options, context, filter, pref) {
402
515
  */
403
516
 
404
517
  function _appendError(error, query, key, aggregatedError) {
518
+ // Set the model on cast errors so `{MODEL}` gets replaced, like it is for
519
+ // query filter casting and document validation (gh-8300). `query` is a
520
+ // Query, or the model itself when casting a `bulkWrite()` operation.
521
+ const model = query?.modelName != null ? query : query?.model;
522
+ if (model != null && typeof error.setModel === 'function') {
523
+ error.setModel(model);
524
+ }
525
+
405
526
  if (typeof query !== 'object' || !query.options.multipleCastError) {
406
527
  throw error;
407
528
  }
@@ -456,11 +577,11 @@ const overwriteOps = {
456
577
  * Casts `val` according to `schema` and atomic `op`.
457
578
  *
458
579
  * @param {SchemaType} schema
459
- * @param {Object} val
460
- * @param {String} op the atomic operator ($pull, $set, etc)
461
- * @param {String} $conditional
580
+ * @param {object} val
581
+ * @param {string} op the atomic operator ($pull, $set, etc)
582
+ * @param {string} $conditional
462
583
  * @param {Query} context
463
- * @param {String} path
584
+ * @param {string} path
464
585
  * @api private
465
586
  */
466
587
 
@@ -470,17 +591,16 @@ function castUpdateVal(schema, val, op, $conditional, context, path) {
470
591
  if (op in numberOps) {
471
592
  try {
472
593
  return castNumber(val);
473
- } catch (err) {
594
+ } catch {
474
595
  throw new CastError('number', val, path);
475
596
  }
476
597
  }
477
598
  return val;
478
599
  }
479
600
 
480
- // console.log('CastUpdateVal', path, op, val, schema);
481
-
482
- const cond = schema.caster && op in castOps &&
483
- (utils.isObject(val) || Array.isArray(val));
601
+ const cond = schema.$isMongooseArray
602
+ && op in castOps
603
+ && (utils.isObject(val) || Array.isArray(val));
484
604
  if (cond && !overwriteOps[op]) {
485
605
  // Cast values for ops that add data to MongoDB.
486
606
  // Ensures embedded documents get ObjectIds etc.
@@ -488,7 +608,7 @@ function castUpdateVal(schema, val, op, $conditional, context, path) {
488
608
  let cur = schema;
489
609
  while (cur.$isMongooseArray) {
490
610
  ++schemaArrayDepth;
491
- cur = cur.caster;
611
+ cur = cur.embeddedSchemaType;
492
612
  }
493
613
  let arrayDepth = 0;
494
614
  let _val = val;
@@ -521,14 +641,15 @@ function castUpdateVal(schema, val, op, $conditional, context, path) {
521
641
  }
522
642
  if (op === '$inc') {
523
643
  // Support `$inc` with long, int32, etc. (gh-4283)
524
- return schema.castForQueryWrapper({
525
- val: val,
526
- context: context
527
- });
644
+ return schema.castForQuery(
645
+ null,
646
+ val,
647
+ context
648
+ );
528
649
  }
529
650
  try {
530
651
  return castNumber(val);
531
- } catch (error) {
652
+ } catch {
532
653
  throw new CastError('number', val, schema.path);
533
654
  }
534
655
  }
@@ -539,22 +660,29 @@ function castUpdateVal(schema, val, op, $conditional, context, path) {
539
660
  return Boolean(val);
540
661
  }
541
662
 
542
- if (/^\$/.test($conditional)) {
543
- return schema.castForQueryWrapper({
544
- $conditional: $conditional,
545
- val: val,
546
- context: context
547
- });
663
+ if (mongodbUpdateOperators.has($conditional)) {
664
+ return schema.castForQuery(
665
+ $conditional,
666
+ val,
667
+ context
668
+ );
548
669
  }
549
670
 
550
671
  if (overwriteOps[op]) {
551
- return schema.castForQueryWrapper({
552
- val: val,
553
- context: context,
554
- $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/),
555
- $applySetters: schema[schemaMixedSymbol] != null
556
- });
672
+ const skipQueryCastForUpdate = val != null
673
+ && schema.$isMongooseArray
674
+ && schema.$fullPath != null
675
+ && !schema.$fullPath.match(/\d+$/);
676
+ const applySetters = schema[schemaMixedSymbol] != null;
677
+ if (skipQueryCastForUpdate || applySetters) {
678
+ return schema.applySetters(val, context);
679
+ }
680
+ return schema.castForQuery(
681
+ null,
682
+ val,
683
+ context
684
+ );
557
685
  }
558
686
 
559
- return schema.castForQueryWrapper({ val: val, context: context });
687
+ return schema.castForQuery(null, val, context);
560
688
  }
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ const PopulateOptions = require('../../options/populateOptions');
4
+ const clone = require('../clone');
5
+ const specialProperties = require('../specialProperties');
6
+
7
+ /*!
8
+ * Deep clone a query's `_mongooseOptions` so a cloned query doesn't share state with the
9
+ * original. `clone()` returns class instances as-is, so explicitly copy `PopulateOptions`,
10
+ * including nested populate: populate options are mutable, and executing a query writes
11
+ * per-execution state like `session` and `lean` into them.
12
+ */
13
+
14
+ module.exports = function cloneMongooseOptions(mongooseOptions) {
15
+ const { populate, ...rest } = mongooseOptions;
16
+ const ret = clone(rest);
17
+ if (populate != null) {
18
+ ret.populate = {};
19
+ for (const path of Object.keys(populate)) {
20
+ if (specialProperties.has(path)) {
21
+ continue;
22
+ }
23
+ ret.populate[path] = clonePopulate(populate[path]);
24
+ }
25
+ }
26
+ return ret;
27
+ };
28
+
29
+ function clonePopulate(pop) {
30
+ if (Array.isArray(pop)) {
31
+ return pop.map(clonePopulate);
32
+ }
33
+ if (pop == null || typeof pop !== 'object') {
34
+ return pop;
35
+ }
36
+
37
+ // Skip `_docs` and `_childDocs`: they hold results of previous executions, see gh-11641
38
+ const { populate, _docs, _childDocs, ...rest } = pop;
39
+ const ret = pop instanceof PopulateOptions ? new PopulateOptions(rest) : clone(rest);
40
+ if (populate !== undefined) {
41
+ ret.populate = clonePopulate(populate);
42
+ }
43
+ return ret;
44
+ }
@@ -3,32 +3,35 @@
3
3
  const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
4
4
  const get = require('../get');
5
5
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
6
+ const getDiscriminatorValueFromFilter = require('../discriminator/getDiscriminatorValueFromFilter');
6
7
  const updatedPathsByArrayFilter = require('../update/updatedPathsByArrayFilter');
7
8
 
8
9
  /**
9
10
  * Like `schema.path()`, except with a document, because impossible to
10
11
  * determine path type without knowing the embedded discriminator key.
11
12
  * @param {Schema} schema
12
- * @param {Object} [update]
13
- * @param {Object} [filter]
14
- * @param {String} path
15
- * @param {Object} [options]
13
+ * @param {object} [update]
14
+ * @param {object} [filter]
15
+ * @param {string} path
16
+ * @param {object} [options]
16
17
  * @api private
17
18
  */
18
19
 
19
20
  module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path, options) {
20
- const parts = path.split('.');
21
+ const parts = path.indexOf('.') === -1 ? [path] : path.split('.');
21
22
  let schematype = null;
22
23
  let type = 'adhocOrUndefined';
23
24
 
24
25
  filter = filter || {};
25
26
  update = update || {};
26
- const arrayFilters = options != null && Array.isArray(options.arrayFilters) ?
27
+ const arrayFilters = Array.isArray(options?.arrayFilters) ?
27
28
  options.arrayFilters : [];
28
29
  const updatedPathsByFilter = updatedPathsByArrayFilter(update);
30
+ let startIndex = 0;
29
31
 
30
32
  for (let i = 0; i < parts.length; ++i) {
31
- const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.'));
33
+ const originalSubpath = parts.slice(startIndex, i + 1).join('.');
34
+ const subpath = cleanPositionalOperators(originalSubpath);
32
35
  schematype = schema.path(subpath);
33
36
  if (schematype == null) {
34
37
  continue;
@@ -44,16 +47,21 @@ module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, p
44
47
  let discriminatorKey = null;
45
48
 
46
49
  if (discriminatorValuePath in filter) {
47
- discriminatorKey = filter[discriminatorValuePath];
50
+ discriminatorKey = getDiscriminatorValueFromFilter(filter[discriminatorValuePath]);
48
51
  }
49
52
  if (discriminatorFilterPath in filter) {
50
- discriminatorKey = filter[discriminatorFilterPath];
53
+ discriminatorKey = getDiscriminatorValueFromFilter(filter[discriminatorFilterPath]);
51
54
  }
52
55
 
53
56
  const wrapperPath = subpath.replace(/\.\d+$/, '');
54
57
  if (schematype.$isMongooseDocumentArrayElement &&
55
58
  get(filter[wrapperPath], '$elemMatch.' + key) != null) {
56
- discriminatorKey = filter[wrapperPath].$elemMatch[key];
59
+ discriminatorKey = getDiscriminatorValueFromFilter(filter[wrapperPath].$elemMatch[key]);
60
+ }
61
+
62
+ const discriminatorKeyUpdatePath = originalSubpath + '.' + key;
63
+ if (discriminatorKeyUpdatePath in update) {
64
+ discriminatorKey = update[discriminatorKeyUpdatePath];
57
65
  }
58
66
 
59
67
  if (discriminatorValuePath in update) {
@@ -64,7 +72,7 @@ module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, p
64
72
  const schemaKey = updatedPathsByFilter[filterKey] + '.' + key;
65
73
  const arrayFilterKey = filterKey + '.' + key;
66
74
  if (schemaKey === discriminatorFilterPath) {
67
- const filter = arrayFilters.find(filter => filter.hasOwnProperty(arrayFilterKey));
75
+ const filter = arrayFilters.find(filter => Object.hasOwn(filter, arrayFilterKey));
68
76
  if (filter != null) {
69
77
  discriminatorKey = filter[arrayFilterKey];
70
78
  }
@@ -75,10 +83,16 @@ module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, p
75
83
  continue;
76
84
  }
77
85
 
78
- const discriminatorSchema = getDiscriminatorByValue(schematype.caster.discriminators, discriminatorKey).schema;
86
+ const discriminator = getDiscriminatorByValue(schematype.Constructor.discriminators, discriminatorKey);
87
+ const discriminatorSchema = discriminator?.schema;
88
+ if (discriminatorSchema == null) {
89
+ continue;
90
+ }
79
91
 
80
92
  const rest = parts.slice(i + 1).join('.');
81
- schematype = discriminatorSchema.path(rest);
93
+ schematype = discriminatorSchema._getSchema(rest);
94
+ schema = discriminatorSchema;
95
+ startIndex = i + 1;
82
96
  if (schematype != null) {
83
97
  type = discriminatorSchema._getPathType(rest);
84
98
  break;