mongoose 9.12.2 → 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 (56) hide show
  1. package/lib/aggregate.js +4 -0
  2. package/lib/cast.js +4 -2
  3. package/lib/connection.js +11 -8
  4. package/lib/defaults/schemaDefaultsCache.js +62 -0
  5. package/lib/document.js +69 -53
  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/cast$expr.js +16 -0
  22. package/lib/helpers/query/castUpdate.js +5 -3
  23. package/lib/helpers/query/sanitizeFilter.js +2 -1
  24. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  25. package/lib/helpers/update/castArrayFilters.js +6 -5
  26. package/lib/helpers/update/removeUnusedArrayFilters.js +4 -0
  27. package/lib/helpers/updateValidators.js +16 -2
  28. package/lib/index.js +7 -0
  29. package/lib/internal.js +4 -0
  30. package/lib/model.js +28 -12
  31. package/lib/mongoose.js +17 -3
  32. package/lib/query.js +74 -7
  33. package/lib/schema/array.js +4 -2
  34. package/lib/schema/bigint.js +2 -1
  35. package/lib/schema/boolean.js +2 -1
  36. package/lib/schema/buffer.js +10 -13
  37. package/lib/schema/date.js +2 -1
  38. package/lib/schema/documentArray.js +18 -10
  39. package/lib/schema/int32.js +2 -1
  40. package/lib/schema/number.js +2 -1
  41. package/lib/schema/string.js +2 -1
  42. package/lib/schema/subdocument.js +2 -1
  43. package/lib/schema/uuid.js +2 -1
  44. package/lib/schema.js +58 -40
  45. package/lib/schemaType.js +9 -2
  46. package/lib/types/array/methods/index.js +81 -3
  47. package/lib/types/map.js +8 -7
  48. package/lib/types/subdocument.js +5 -1
  49. package/lib/utils.js +8 -6
  50. package/package.json +3 -3
  51. package/types/expressions.d.ts +1 -1
  52. package/types/index.d.ts +3 -0
  53. package/types/models.d.ts +12 -4
  54. package/types/query.d.ts +1 -1
  55. package/types/schemaoptions.d.ts +7 -0
  56. package/types/utility.d.ts +117 -5
package/lib/model.js CHANGED
@@ -49,7 +49,9 @@ const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchema
49
49
  const discriminator = require('./helpers/model/discriminator');
50
50
  const each = require('./helpers/each');
51
51
  const get = require('./helpers/get');
52
+ const getOwnProperty = require('./helpers/getOwnProperty');
52
53
  const getConstructorName = require('./helpers/getConstructorName');
54
+ const isMongooseDocument = require('./helpers/isMongooseDocument');
53
55
  const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
54
56
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
55
57
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
@@ -624,7 +626,7 @@ function generateVersionError(doc, modifiedPaths, defaultPaths) {
624
626
  * @param {number|string} [options.w] set the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
625
627
  * @param {boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
626
628
  * @param {number} [options.wtimeout] sets a [timeout for the write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern).
627
- * @param {boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Restrictions-on-Field-Names)
629
+ * @param {boolean} [options.checkKeys=false] if `true`, the MongoDB driver rejects keys that start with '$' or contain '.' when this `save()` inserts a new document. Leave it off when saving changes to an existing document: the driver also checks update operators like `$set`, so the update fails. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#mongodb-limit-Restrictions-on-Field-Names)
628
630
  * @param {boolean} [options.timestamps=true] if `false` and [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this `save()`.
629
631
  * @param {Array} [options.pathsToSave] An array of paths that tell mongoose to only validate and save the paths in `pathsToSave`.
630
632
  * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
@@ -952,8 +954,10 @@ Model.exists = function exists(filter, options) {
952
954
  throw new MongooseError('Model.exists() no longer accepts a callback');
953
955
  }
954
956
 
957
+ // Which document matches doesn't matter, and a `defaultSort` would make MongoDB find every match.
955
958
  const query = this.findOne(filter).
956
959
  select({ _id: 1 }).
960
+ sort(null).
957
961
  lean().
958
962
  setOptions(options);
959
963
 
@@ -1024,7 +1028,7 @@ Model.discriminator = function(name, schema, options) {
1024
1028
  }
1025
1029
 
1026
1030
  schema = discriminator(this, name, schema, value, mergePlugins, options.mergeHooks, overwriteModels);
1027
- if (this.db.models[name] && !schema.options.overwriteModels && !overwriteModels) {
1031
+ if (getOwnProperty(this.db.models, name) && !schema.options.overwriteModels && !overwriteModels) {
1028
1032
  throw new OverwriteModelError(name);
1029
1033
  }
1030
1034
 
@@ -2140,6 +2144,8 @@ Model.find = function find(conditions, projection, options) {
2140
2144
  * Finds documents and counts the number of documents matching the filter.
2141
2145
  *
2142
2146
  * This function fires both `find` and `countDocuments` middleware.
2147
+ * Requires `options.limit`, and requires `options.sort` unless the schema has a [`defaultSort`](https://mongoosejs.com/docs/guide.html#defaultSort).
2148
+ * Throws if `options.sort` is empty, like `sort: null`.
2143
2149
  *
2144
2150
  * #### Example:
2145
2151
  *
@@ -2165,14 +2171,20 @@ Model.findAndCount = async function findAndCount(conditions, projection, options
2165
2171
  if (options == null) {
2166
2172
  throw new MongooseError('Model.findAndCount() requires an `options` argument with `sort` and `limit`');
2167
2173
  }
2168
- if (options.sort == null) {
2174
+ const findQuery = this.find(conditions, projection, options);
2175
+ if (options.sort == null && !this.schema.options.defaultSort) {
2169
2176
  throw new MongooseError('Model.findAndCount() requires `options.sort`');
2170
2177
  }
2178
+ // `sort: null`, `sort: undefined`, and `sort: {}` all mean "no sort".
2179
+ // This catches explicitly setting `sort: null`, `sort: undefined`, or
2180
+ // `sort: {}` in `options`.
2181
+ if (utils.isEmptyObject(findQuery.options.sort)) {
2182
+ throw new MongooseError('Model.findAndCount() does not allow an empty `options.sort`, like `sort: null`. Omit `options.sort` to use the schema\'s `defaultSort`.');
2183
+ }
2171
2184
  if (options.limit == null) {
2172
2185
  throw new MongooseError('Model.findAndCount() requires `options.limit`');
2173
2186
  }
2174
2187
 
2175
- const findQuery = this.find(conditions, projection, options);
2176
2188
  const countQuery = findQuery.clone().countDocuments().skip(0).limit(null);
2177
2189
 
2178
2190
  return Promise.all([findQuery.exec(), countQuery.exec()]);
@@ -3765,7 +3777,7 @@ Model.applyDefaults = function applyDefaults(doc) {
3765
3777
  if (doc == null) {
3766
3778
  return doc;
3767
3779
  }
3768
- if (doc.$__ != null) {
3780
+ if (isMongooseDocument(doc)) {
3769
3781
  applyDefaultsHelper(doc, doc.$__.fields, doc.$__.exclude);
3770
3782
 
3771
3783
  for (const subdoc of doc.$getAllSubdocs()) {
@@ -3805,7 +3817,7 @@ Model.applyVirtuals = function applyVirtuals(obj, virtualsToApply) {
3805
3817
  return obj;
3806
3818
  }
3807
3819
  // Nothing to do if this is already a hydrated document - it should already have virtuals
3808
- if (obj.$__ != null) {
3820
+ if (isMongooseDocument(obj)) {
3809
3821
  return obj;
3810
3822
  }
3811
3823
 
@@ -3840,7 +3852,7 @@ Model.applyTimestamps = function applyTimestamps(obj, options) {
3840
3852
  return obj;
3841
3853
  }
3842
3854
  // Nothing to do if this is already a hydrated document - it should already have timestamps
3843
- if (obj.$__ != null) {
3855
+ if (isMongooseDocument(obj)) {
3844
3856
  return obj;
3845
3857
  }
3846
3858
 
@@ -4080,7 +4092,7 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
4080
4092
  * @param {boolean} [options.setters=false] if true, apply schema setters when hydrating
4081
4093
  * @param {boolean} [options.hydratedPopulatedDocs=false] if true, populates the docs if passing pre-populated data
4082
4094
  * @param {boolean} [options.virtuals=false] if true, sets any virtuals present on `obj`
4083
- * @param {boolean|'throw'} [options.strict=false] configure strict mode for the hydrated document. In particular, if strict is false, fields not in the schema won't be stripped out; if strict is 'throw', `hydrate()` will throw an error if there are any fields that are not in the schema. Defaults to true (silently strip out fields not in the schema).
4095
+ * @param {boolean|'throw'} [options.strict] configure strict mode for the hydrated document. In particular, if strict is false, fields not in the schema won't be stripped out; if strict is 'throw', `hydrate()` will throw an error if there are any fields that are not in the schema. Falls back to the schema's [`strict` option](https://mongoosejs.com/docs/guide.html#strict) if this option is nullish, which is true by default (silently strip out fields not in the schema).
4084
4096
  * @return {Document} document instance
4085
4097
  * @api public
4086
4098
  */
@@ -4093,7 +4105,7 @@ Model.hydrate = function hydrate(obj, projection, options) {
4093
4105
  }
4094
4106
 
4095
4107
  if (projection != null) {
4096
- if (obj?.$__ != null) {
4108
+ if (isMongooseDocument(obj)) {
4097
4109
  obj = obj.toObject(internalToObjectOptions);
4098
4110
  }
4099
4111
  projection = parseProjection(projection);
@@ -4388,7 +4400,9 @@ Model.validate = async function validate(obj, pathsOrOptions, context) {
4388
4400
  return false;
4389
4401
  }
4390
4402
  } else if (typeof pathsOrOptions.pathsToSkip == 'string') {
4391
- if (pathsOrOptions.pathsToSkip.includes(p)) {
4403
+ if (pathsOrOptions.pathsToSkip.indexOf(' ') !== -1 && pathsOrOptions.pathsToSkip.split(' ').includes(p)) {
4404
+ return false;
4405
+ } else if (pathsOrOptions.pathsToSkip === p) {
4392
4406
  return false;
4393
4407
  }
4394
4408
  }
@@ -4596,7 +4610,7 @@ async function _populatePath(model, docs, populateOptions) {
4596
4610
  }
4597
4611
 
4598
4612
  const modelsMap = getModelsMapForPopulate(model, docs, populateOptions);
4599
- if (modelsMap instanceof MongooseError) {
4613
+ if (modelsMap instanceof Error) {
4600
4614
  throw modelsMap;
4601
4615
  }
4602
4616
  const len = modelsMap.length;
@@ -4771,7 +4785,7 @@ async function _populatePath(model, docs, populateOptions) {
4771
4785
  // `utils.getValue()` rather than a bracket lookup, because `mod.options.path` may be
4772
4786
  // a dotted path like 'children.child', which a lean result does not store as a
4773
4787
  // single key.
4774
- const childVal = doc.$__ != null ? doc.get(mod.options.path) : utils.getValue(mod.options.path, doc);
4788
+ const childVal = isMongooseDocument(doc) ? doc.get(mod.options.path) : utils.getValue(mod.options.path, doc);
4775
4789
  if (Array.isArray(childVal)) {
4776
4790
  childDocsToPopulate.push(...childVal);
4777
4791
  } else if (childVal != null) {
@@ -4835,6 +4849,8 @@ function _execPopulateQuery(mod, match, select) {
4835
4849
 
4836
4850
  if (mod.count) {
4837
4851
  delete queryOptions.skip;
4852
+ // Sort doesn't affect the count, so skip the ref model's `defaultSort`
4853
+ queryOptions.sort ??= {};
4838
4854
  }
4839
4855
 
4840
4856
  if (queryOptions.perDocumentLimit != null) {
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.');
@@ -429,7 +429,8 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
429
429
  const path = options.path || this.path;
430
430
 
431
431
  if (!Array.isArray(value)) {
432
- if (!init && !SchemaDocumentArray.options.castNonArrays) {
432
+ const castNonArraysOption = this.options.castNonArrays ?? SchemaDocumentArray.options.castNonArrays;
433
+ if (!init && !castNonArraysOption) {
433
434
  throw new CastError('DocumentArray', value, this.path, null, this);
434
435
  }
435
436
  // gh-2442 mark whole array as modified if we're initializing a doc from
@@ -504,15 +505,12 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
504
505
  }
505
506
  rawArray[i] = subdoc.$init(rawArray[i], options);
506
507
  } else {
507
- if (typeof prev?.id === 'function') {
508
- subdoc = prev.id(rawArray[i]._id);
509
- }
510
-
511
- if (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
512
- // handle resetting doc with existing id and same data
513
- subdoc.set(rawArray[i]);
514
- // if set() is hooked it will have no return value
515
- // 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])) {
516
514
  rawArray[i] = subdoc;
517
515
  } else {
518
516
  try {
@@ -530,6 +528,16 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
530
528
  }
531
529
  }
532
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
+
533
541
  return value;
534
542
  };
535
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);