mongoose 9.12.3 → 9.13.0

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 (53) hide show
  1. package/lib/aggregate.js +4 -0
  2. package/lib/cast.js +4 -2
  3. package/lib/connection.js +10 -7
  4. package/lib/defaults/schemaDefaultsCache.js +62 -0
  5. package/lib/document.js +68 -52
  6. package/lib/filters/operators.js +8 -0
  7. package/lib/helpers/clone.js +9 -8
  8. package/lib/helpers/document/applyDefaults.js +1 -1
  9. package/lib/helpers/document/compile.js +2 -1
  10. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  11. package/lib/helpers/getInheritedProperty.js +28 -0
  12. package/lib/helpers/getOwnProperty.js +19 -0
  13. package/lib/helpers/isMongooseDocument.js +24 -0
  14. package/lib/helpers/isMongooseObject.js +5 -3
  15. package/lib/helpers/model/discriminator.js +9 -3
  16. package/lib/helpers/parallelLimit.js +31 -11
  17. package/lib/helpers/populate/assignVals.js +10 -8
  18. package/lib/helpers/populate/getModelsMapForPopulate.js +9 -7
  19. package/lib/helpers/populate/getSchemaTypes.js +2 -1
  20. package/lib/helpers/populate/removeDeselectedForeignField.js +2 -1
  21. package/lib/helpers/query/castUpdate.js +5 -3
  22. package/lib/helpers/query/sanitizeFilter.js +2 -1
  23. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  24. package/lib/helpers/update/castArrayFilters.js +6 -5
  25. package/lib/helpers/update/removeUnusedArrayFilters.js +4 -0
  26. package/lib/helpers/updateValidators.js +2 -1
  27. package/lib/index.js +7 -0
  28. package/lib/internal.js +4 -0
  29. package/lib/model.js +24 -10
  30. package/lib/mongoose.js +17 -3
  31. package/lib/query.js +74 -7
  32. package/lib/schema/array.js +4 -2
  33. package/lib/schema/bigint.js +2 -1
  34. package/lib/schema/boolean.js +2 -1
  35. package/lib/schema/buffer.js +10 -13
  36. package/lib/schema/date.js +2 -1
  37. package/lib/schema/documentArray.js +16 -9
  38. package/lib/schema/int32.js +2 -1
  39. package/lib/schema/number.js +2 -1
  40. package/lib/schema/string.js +2 -1
  41. package/lib/schema/subdocument.js +2 -1
  42. package/lib/schema/uuid.js +2 -1
  43. package/lib/schema.js +58 -40
  44. package/lib/schemaType.js +9 -2
  45. package/lib/types/array/methods/index.js +81 -3
  46. package/lib/types/map.js +8 -7
  47. package/lib/types/subdocument.js +5 -1
  48. package/lib/utils.js +8 -6
  49. package/package.json +2 -2
  50. package/types/models.d.ts +12 -4
  51. package/types/query.d.ts +1 -1
  52. package/types/schemaoptions.d.ts +7 -0
  53. package/types/utility.d.ts +117 -5
package/lib/mongoose.js CHANGED
@@ -28,6 +28,7 @@ const Aggregate = require('./aggregate');
28
28
  const trusted = require('./helpers/query/trusted').trusted;
29
29
  const sanitizeFilter = require('./helpers/query/sanitizeFilter');
30
30
  const isBsonType = require('./helpers/isBsonType');
31
+ const getOwnProperty = require('./helpers/getOwnProperty');
31
32
  const MongooseError = require('./error/mongooseError');
32
33
  const SetOptionError = require('./error/setOptionError');
33
34
  const applyEmbeddedDiscriminators = require('./helpers/discriminator/applyEmbeddedDiscriminators');
@@ -457,8 +458,8 @@ Mongoose.prototype.createConnection = function createConnection(uri, options) {
457
458
  * @param {string} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
458
459
  * @param {number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
459
460
  * @param {number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection.
460
- * @param {number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
461
- * @param {number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
461
+ * @param {number} [options.serverSelectionTimeoutMS] The MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
462
+ * @param {number} [options.heartbeatFrequencyMS] The MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
462
463
  * @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
463
464
  * @param {number} [options.socketTimeoutMS=0] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. `socketTimeoutMS` defaults to 0, which means Node.js will not time out the socket due to inactivity. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
464
465
  * @param {number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
@@ -604,7 +605,7 @@ Mongoose.prototype.model = function model(name, schema, collection, options) {
604
605
  }
605
606
 
606
607
  if (arguments.length === 1) {
607
- const model = _mongoose.models[name];
608
+ const model = getOwnProperty(_mongoose.models, name);
608
609
  if (!model) {
609
610
  throw new _mongoose.Error.MissingSchemaError(name);
610
611
  }
@@ -676,6 +677,10 @@ Mongoose.prototype._model = function _model(name, schema, collection, options) {
676
677
  throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
677
678
  }
678
679
  }
680
+ // Models are stored in POJOs keyed by name, so `__proto__` would change their prototype
681
+ if (name === '__proto__') {
682
+ throw new _mongoose.Error('Model name "__proto__" is not allowed');
683
+ }
679
684
 
680
685
  if (schema) {
681
686
  if (_mongoose.get('cloneSchemas')) {
@@ -1274,6 +1279,15 @@ Mongoose.prototype.CastError = MongooseError.CastError;
1274
1279
 
1275
1280
  Mongoose.prototype.SchemaTypeOptions = require('./options/schemaTypeOptions');
1276
1281
 
1282
+ /**
1283
+ * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
1284
+ *
1285
+ * @property mongo
1286
+ * @api public
1287
+ */
1288
+
1289
+ Mongoose.prototype.mongo = null;
1290
+
1277
1291
  /**
1278
1292
  * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
1279
1293
  *
package/lib/query.js CHANGED
@@ -27,8 +27,10 @@ const helpers = require('./queryHelpers');
27
27
  const internalToObjectOptions = require('./options').internalToObjectOptions;
28
28
  const isExclusive = require('./helpers/projection/isExclusive');
29
29
  const isInclusive = require('./helpers/projection/isInclusive');
30
+ const isMongooseDocument = require('./helpers/isMongooseDocument');
30
31
  const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
31
32
  const isSubpath = require('./helpers/projection/isSubpath');
33
+ const { logicalOperators } = require('./filters/operators');
32
34
  const mpath = require('mpath');
33
35
  const mquery = require('mquery');
34
36
  const parseProjection = require('./helpers/projection/parseProjection');
@@ -70,6 +72,18 @@ const queryOptionMethods = new Set([
70
72
  'wtimeout'
71
73
  ]);
72
74
 
75
+ // Operations that the schema-level `defaultSort` option applies to. These are the operations where
76
+ // sort determines the result. `deleteOne()` and `updateMany()` are excluded because the MongoDB driver
77
+ // silently ignores `sort` for those operations. `updateOne()` and `replaceOne()` are excluded because
78
+ // MongoDB < 8.0 throws an error if `sort` is set for those operations.
79
+ const defaultSortOps = new Set([
80
+ 'find',
81
+ 'findOne',
82
+ 'findOneAndDelete',
83
+ 'findOneAndReplace',
84
+ 'findOneAndUpdate'
85
+ ]);
86
+
73
87
  // Map from operation name to the name of the function that executes the actual operation against MongoDB.
74
88
  // Called a thunk for legacy reasons, "thunk" means function that takes exactly 1 param, a callback.
75
89
  // Currently `_countDocuments()`, etc. are async functions that take no params.
@@ -1704,7 +1718,7 @@ Query.prototype.getOptions = function() {
1704
1718
  *
1705
1719
  * - [maxTimeMS](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/)
1706
1720
  *
1707
- * The following options are for `find()`, `findOne()`, `findOneAndUpdate()`, `findOneAndDelete()`, `updateOne()`, and `deleteOne()`:
1721
+ * The following options are for `find()`, `findOne()`, `findOneAndUpdate()`, `findOneAndDelete()`, `findOneAndReplace()`, `updateOne()`, and `replaceOne()`:
1708
1722
  *
1709
1723
  * - [sort](https://www.mongodb.com/docs/manual/reference/method/cursor.sort/)
1710
1724
  *
@@ -2127,6 +2141,19 @@ Query.prototype._optionsForExec = function(model) {
2127
2141
  if (!model) {
2128
2142
  return options;
2129
2143
  }
2144
+ if (utils.isEmptyObject(options.sort)) {
2145
+ // Empty sort means "no sort". The driver would send `sort: null` for `updateOne()` and
2146
+ // `replaceOne()`, which MongoDB < 8.0 rejects.
2147
+ delete options.sort;
2148
+ } else if (options.sort == null && !options.tailable && defaultSortOps.has(this.op)) {
2149
+ // Apply `defaultSort` to the options we send to MongoDB rather than to `this.options`, so an
2150
+ // explicit `sort()` on a clone of this query replaces the default instead of merging with it.
2151
+ // Tailable cursors can't sort, and `$near` queries already sort by distance.
2152
+ const defaultSort = this.schema?.options.defaultSort;
2153
+ if (defaultSort && !_hasNearCondition(this._conditions)) {
2154
+ options.sort = _addSortKeys({}, defaultSort);
2155
+ }
2156
+ }
2130
2157
  applyReadConcern(model.schema, options);
2131
2158
  // Apply schema-level `writeConcern` option
2132
2159
  applyWriteConcern(model.schema, options);
@@ -2538,6 +2565,8 @@ Query.prototype.find = function(conditions) {
2538
2565
  * Executes the query as a `find()` and also runs a `countDocuments()` query
2539
2566
  * on the same filter, returning `[documents, count]`. The count ignores
2540
2567
  * `skip` and `limit` so that it returns the total number of matching documents.
2568
+ * Requires `limit`, and requires `sort` unless the schema has a [`defaultSort`](https://mongoosejs.com/docs/guide.html#defaultSort).
2569
+ * Throws if `sort` is empty, like `sort(null)`.
2541
2570
  *
2542
2571
  * #### Example:
2543
2572
  *
@@ -2549,9 +2578,13 @@ Query.prototype.find = function(conditions) {
2549
2578
  */
2550
2579
 
2551
2580
  Query.prototype.findAndCount = async function findAndCount() {
2552
- if (this.options.sort == null) {
2581
+ if (this.options.sort == null && !this.schema?.options.defaultSort) {
2553
2582
  throw new MongooseError('Query.prototype.findAndCount() requires sort. Use `sort()` to set a sort order before calling `findAndCount()`.');
2554
2583
  }
2584
+ // `sort(null)`, `sort(undefined)`, and `sort({})` all mean "no sort", which would make pagination unstable
2585
+ if (utils.isEmptyObject(this.options.sort)) {
2586
+ throw new MongooseError('Query.prototype.findAndCount() does not allow an empty sort, like `sort(null)`. Remove the `sort()` call to use the schema\'s `defaultSort`.');
2587
+ }
2555
2588
  if (this.options.limit == null) {
2556
2589
  throw new MongooseError('Query.prototype.findAndCount() requires limit. Use `limit()` to set a limit before calling `findAndCount()`.');
2557
2590
  }
@@ -2627,7 +2660,7 @@ Query.prototype.merge = function(source) {
2627
2660
  utils.merge(this._conditions, { _id: source }, opts);
2628
2661
 
2629
2662
  return this;
2630
- } else if (source?.$__) {
2663
+ } else if (isMongooseDocument(source)) {
2631
2664
  source = source.toObject(internalToObjectOptions);
2632
2665
  }
2633
2666
 
@@ -3120,6 +3153,9 @@ Query.prototype.distinct = function(field, conditions, options) {
3120
3153
  * // also possible is to use a array with array key-value pairs
3121
3154
  * query.sort([['field', 'asc']]);
3122
3155
  *
3156
+ * // run this query with no sort, ignoring the schema's `defaultSort`
3157
+ * query.sort(null);
3158
+ *
3123
3159
  * #### Note:
3124
3160
  *
3125
3161
  * Cannot be used with `distinct()`
@@ -3146,7 +3182,37 @@ Query.prototype.sort = function(arg, options) {
3146
3182
  if (options?.override) {
3147
3183
  this.options.sort = {};
3148
3184
  }
3149
- const sort = this.options.sort;
3185
+ _addSortKeys(this.options.sort, arg);
3186
+
3187
+ return this;
3188
+ };
3189
+
3190
+ /*!
3191
+ * Returns true if `filter` has a `$near` or `$nearSphere` condition, including within logical operators.
3192
+ */
3193
+
3194
+ function _hasNearCondition(filter) {
3195
+ for (const key of Object.keys(filter)) {
3196
+ const val = filter[key];
3197
+ if (val == null || typeof val !== 'object') {
3198
+ continue;
3199
+ }
3200
+ if (logicalOperators.has(key)) {
3201
+ if (Array.isArray(val) && val.some(clause => clause != null && typeof clause === 'object' && _hasNearCondition(clause))) {
3202
+ return true;
3203
+ }
3204
+ } else if (Object.hasOwn(val, '$near') || Object.hasOwn(val, '$nearSphere')) {
3205
+ return true;
3206
+ }
3207
+ }
3208
+ return false;
3209
+ }
3210
+
3211
+ /*!
3212
+ * Add the keys from `arg`, which can be any value that `Query.prototype.sort()` accepts, to the `sort` object.
3213
+ */
3214
+
3215
+ function _addSortKeys(sort, arg) {
3150
3216
  if (typeof arg === 'string') {
3151
3217
  const properties = arg.indexOf(' ') === -1 ? [arg] : arg.split(' ');
3152
3218
  for (let property of properties) {
@@ -3189,8 +3255,8 @@ Query.prototype.sort = function(arg, options) {
3189
3255
  throw new TypeError('Invalid sort() argument. Must be a string, object, array, or map.');
3190
3256
  }
3191
3257
 
3192
- return this;
3193
- };
3258
+ return sort;
3259
+ }
3194
3260
 
3195
3261
  /*!
3196
3262
  * Convert sort values
@@ -3203,7 +3269,8 @@ function _handleSortValue(val, key) {
3203
3269
  if (val === -1 || val === 'desc' || val === 'descending') {
3204
3270
  return -1;
3205
3271
  }
3206
- if (val?.$meta != null) {
3272
+ // Only own `$meta`, because the MongoDB driver only reads own properties
3273
+ if (val != null && Object.hasOwn(val, '$meta') && val.$meta != null) {
3207
3274
  return { $meta: val.$meta };
3208
3275
  }
3209
3276
  throw new TypeError('Invalid sort value: { ' + key + ': ' + val + ' }');
@@ -24,6 +24,7 @@ const castToNumber = require('./operators/helpers').castToNumber;
24
24
  const geospatial = require('./operators/geospatial');
25
25
  const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
26
26
  const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
27
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
27
28
 
28
29
  let MongooseArray;
29
30
  let EmbeddedDoc;
@@ -295,8 +296,9 @@ SchemaArray.prototype.applyGetters = function(value, scope) {
295
296
  };
296
297
 
297
298
  SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) {
299
+ const castNonArraysOption = this.options.castNonArrays ?? SchemaArray.options.castNonArrays;
298
300
  if (this.embeddedSchemaType.$isMongooseArray &&
299
- SchemaArray.options.castNonArrays) {
301
+ castNonArraysOption) {
300
302
  // Check nesting levels and wrap in array if necessary
301
303
  let depth = 0;
302
304
  let arr = this;
@@ -548,7 +550,7 @@ SchemaArray.prototype.castForQuery = function($conditional, val, context) {
548
550
  let handler;
549
551
 
550
552
  if ($conditional != null) {
551
- handler = this.$conditionalHandlers[$conditional];
553
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
552
554
 
553
555
  if (!handler) {
554
556
  throw new Error('Can\'t use ' + $conditional + ' with Array.');
@@ -7,6 +7,7 @@
7
7
  const CastError = require('../error/cast');
8
8
  const SchemaType = require('../schemaType');
9
9
  const castBigInt = require('../cast/bigint');
10
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
10
11
 
11
12
  /**
12
13
  * BigInt SchemaType constructor.
@@ -220,7 +221,7 @@ function handleSingle(val, context) {
220
221
  SchemaBigInt.prototype.castForQuery = function($conditional, val, context) {
221
222
  let handler;
222
223
  if ($conditional != null) {
223
- handler = this.$conditionalHandlers[$conditional];
224
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
224
225
 
225
226
  if (handler) {
226
227
  return handler.call(this, val);
@@ -7,6 +7,7 @@
7
7
  const CastError = require('../error/cast');
8
8
  const SchemaType = require('../schemaType');
9
9
  const castBoolean = require('../cast/boolean');
10
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
10
11
 
11
12
  /**
12
13
  * Boolean SchemaType constructor.
@@ -264,7 +265,7 @@ Object.defineProperty(SchemaBoolean.prototype, '$conditionalHandlers', {
264
265
  SchemaBoolean.prototype.castForQuery = function($conditional, val, context) {
265
266
  let handler;
266
267
  if ($conditional != null) {
267
- handler = this.$conditionalHandlers[$conditional];
268
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
268
269
 
269
270
  if (handler) {
270
271
  return handler.call(this, val);
@@ -9,6 +9,7 @@ const SchemaBufferOptions = require('../options/schemaBufferOptions');
9
9
  const SchemaType = require('../schemaType');
10
10
  const handleBitwiseOperator = require('./operators/bitwise');
11
11
  const utils = require('../utils');
12
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
12
13
 
13
14
  const Binary = MongooseBuffer.Binary;
14
15
  const CastError = SchemaType.CastError;
@@ -145,16 +146,14 @@ SchemaBuffer.prototype.checkRequired = function(value, doc) {
145
146
  SchemaBuffer.prototype.cast = function(value, doc, init, prev, options) {
146
147
  let ret;
147
148
  if (SchemaType._isRef(this, value, doc, init)) {
148
- if (value?.isMongooseBuffer) {
149
+ if (Buffer.isBuffer(value) && value.isMongooseBuffer) {
149
150
  return value;
150
151
  }
151
152
 
152
153
  if (Buffer.isBuffer(value)) {
153
- if (!value?.isMongooseBuffer) {
154
- value = new MongooseBuffer(value, [this.path, doc]);
155
- if (this.options.subtype != null) {
156
- value._subtype = this.options.subtype;
157
- }
154
+ value = new MongooseBuffer(value, [this.path, doc]);
155
+ if (this.options.subtype != null) {
156
+ value._subtype = this.options.subtype;
158
157
  }
159
158
  return value;
160
159
  }
@@ -178,16 +177,14 @@ SchemaBuffer.prototype.cast = function(value, doc, init, prev, options) {
178
177
  value = value._id;
179
178
  }
180
179
 
181
- if (value?.isMongooseBuffer) {
180
+ if (Buffer.isBuffer(value) && value.isMongooseBuffer) {
182
181
  return value;
183
182
  }
184
183
 
185
184
  if (Buffer.isBuffer(value)) {
186
- if (!value?.isMongooseBuffer) {
187
- value = new MongooseBuffer(value, [this.path, doc]);
188
- if (this.options.subtype != null) {
189
- value._subtype = this.options.subtype;
190
- }
185
+ value = new MongooseBuffer(value, [this.path, doc]);
186
+ if (this.options.subtype != null) {
187
+ value._subtype = this.options.subtype;
191
188
  }
192
189
  return value;
193
190
  }
@@ -299,7 +296,7 @@ Object.defineProperty(SchemaBuffer.prototype, '$conditionalHandlers', {
299
296
  SchemaBuffer.prototype.castForQuery = function($conditional, val, context) {
300
297
  let handler;
301
298
  if ($conditional != null) {
302
- handler = this.$conditionalHandlers[$conditional];
299
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
303
300
  if (!handler) {
304
301
  throw new Error('Can\'t use ' + $conditional + ' with Buffer.');
305
302
  }
@@ -10,6 +10,7 @@ const SchemaType = require('../schemaType');
10
10
  const castDate = require('../cast/date');
11
11
  const getConstructorName = require('../helpers/getConstructorName');
12
12
  const utils = require('../utils');
13
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
13
14
 
14
15
  const CastError = SchemaType.CastError;
15
16
 
@@ -435,7 +436,7 @@ SchemaDate.prototype.castForQuery = function($conditional, val, context) {
435
436
  }
436
437
  }
437
438
 
438
- const handler = this.$conditionalHandlers[$conditional];
439
+ const handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
439
440
 
440
441
  if (!handler) {
441
442
  throw new Error('Can\'t use ' + $conditional + ' with Date.');
@@ -505,15 +505,12 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
505
505
  }
506
506
  rawArray[i] = subdoc.$init(rawArray[i], options);
507
507
  } else {
508
- if (typeof prev?.id === 'function') {
509
- subdoc = prev.id(rawArray[i]._id);
510
- }
511
-
512
- if (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
513
- // handle resetting doc with existing id and same data
514
- subdoc.set(rawArray[i]);
515
- // if set() is hooked it will have no return value
516
- // see gh-746
508
+ // Reuse the existing subdoc at the same index if it has the same `_id` and data, so
509
+ // references to it stay valid. Only checking the same index keeps this O(n) (gh-16673).
510
+ subdoc = prev?.[i];
511
+ if (subdoc?._doc != null && rawArray[i]._id != null &&
512
+ utils.deepEqual(rawArray[i]._id, subdoc._doc._id) &&
513
+ utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
517
514
  rawArray[i] = subdoc;
518
515
  } else {
519
516
  try {
@@ -531,6 +528,16 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
531
528
  }
532
529
  }
533
530
 
531
+ // A subdoc can only belong to one array, so subdocs reused from `prev` move to the new array,
532
+ // like gh-5189. Only do this after casting succeeded, so a CastError leaves `prev` consistent.
533
+ if (utils.isMongooseDocumentArray(prev)) {
534
+ for (let i = 0; i < len; ++i) {
535
+ if (rawArray[i] != null && rawArray[i] === prev[i]) {
536
+ rawArray[i].__parentArray = value;
537
+ }
538
+ }
539
+ }
540
+
534
541
  return value;
535
542
  };
536
543
 
@@ -8,6 +8,7 @@ const CastError = require('../error/cast');
8
8
  const SchemaType = require('../schemaType');
9
9
  const castInt32 = require('../cast/int32');
10
10
  const handleBitwiseOperator = require('./operators/bitwise');
11
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
11
12
 
12
13
  /**
13
14
  * Int32 SchemaType constructor.
@@ -244,7 +245,7 @@ function handleSingle(val, context) {
244
245
  SchemaInt32.prototype.castForQuery = function($conditional, val, context) {
245
246
  let handler;
246
247
  if ($conditional != null) {
247
- handler = this.$conditionalHandlers[$conditional];
248
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
248
249
 
249
250
  if (handler) {
250
251
  return handler.call(this, val);
@@ -10,6 +10,7 @@ const SchemaType = require('../schemaType');
10
10
  const castNumber = require('../cast/number');
11
11
  const handleBitwiseOperator = require('./operators/bitwise');
12
12
  const utils = require('../utils');
13
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
13
14
 
14
15
  const CastError = SchemaType.CastError;
15
16
 
@@ -476,7 +477,7 @@ Object.defineProperty(SchemaNumber.prototype, '$conditionalHandlers', {
476
477
  SchemaNumber.prototype.castForQuery = function($conditional, val, context) {
477
478
  let handler;
478
479
  if ($conditional != null) {
479
- handler = this.$conditionalHandlers[$conditional];
480
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
480
481
  if (!handler) {
481
482
  throw new MongooseError('Can\'t use ' + $conditional + ' with Number.');
482
483
  }
@@ -10,6 +10,7 @@ const SchemaStringOptions = require('../options/schemaStringOptions');
10
10
  const castString = require('../cast/string');
11
11
  const utils = require('../utils');
12
12
  const isBsonType = require('../helpers/isBsonType');
13
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
13
14
 
14
15
  const CastError = SchemaType.CastError;
15
16
 
@@ -693,7 +694,7 @@ Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', {
693
694
  SchemaString.prototype.castForQuery = function($conditional, val, context) {
694
695
  let handler;
695
696
  if ($conditional != null) {
696
- handler = this.$conditionalHandlers[$conditional];
697
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
697
698
  if (!handler) {
698
699
  throw new Error('Can\'t use ' + $conditional + ' with String.');
699
700
  }
@@ -21,6 +21,7 @@ const internalToObjectOptions = require('../options').internalToObjectOptions;
21
21
  const isExclusive = require('../helpers/projection/isExclusive');
22
22
  const utils = require('../utils');
23
23
  const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
24
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
24
25
 
25
26
  let SubdocumentType;
26
27
 
@@ -237,7 +238,7 @@ SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
237
238
  SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) {
238
239
  let handler;
239
240
  if ($conditional != null) {
240
- handler = this.$conditionalHandlers[$conditional];
241
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
241
242
  if (!handler) {
242
243
  throw new Error('Can\'t use ' + $conditional);
243
244
  }
@@ -9,6 +9,7 @@ const CastError = SchemaType.CastError;
9
9
  const castUUID = require('../cast/uuid');
10
10
  const utils = require('../utils');
11
11
  const handleBitwiseOperator = require('./operators/bitwise');
12
+ const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
12
13
 
13
14
  const UUID_FORMAT = castUUID.UUID_FORMAT;
14
15
 
@@ -264,7 +265,7 @@ Object.defineProperty(SchemaUUID.prototype, '$conditionalHandlers', {
264
265
  SchemaUUID.prototype.castForQuery = function($conditional, val, context) {
265
266
  let handler;
266
267
  if ($conditional != null) {
267
- handler = this.$conditionalHandlers[$conditional];
268
+ handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
268
269
  if (!handler)
269
270
  throw new Error('Can\'t use ' + $conditional + ' with UUID.');
270
271
  return handler.call(this, val, context);