mongoose 9.11.2 → 9.11.4

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.
package/lib/aggregate.js CHANGED
@@ -182,7 +182,6 @@ Aggregate.prototype.append = function() {
182
182
 
183
183
  /**
184
184
  * Appends a new $addFields operator to this aggregate pipeline.
185
- * Requires MongoDB v3.4+ to work
186
185
  *
187
186
  * #### Example:
188
187
  *
package/lib/cast.js CHANGED
@@ -4,6 +4,7 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
7
8
  const CastError = require('./error/cast');
8
9
  const StrictModeError = require('./error/strict');
9
10
  const Types = require('./schema/index');
@@ -138,8 +139,9 @@ module.exports = function cast(schema, obj, options, context) {
138
139
  pathLastHalf !== discriminatorKey) {
139
140
  const discriminatorVal = getDiscriminatorValueFromFilter(get(obj, pathFirstHalf + '.' + discriminatorKey));
140
141
  const discriminators = _schematype.schema.discriminators;
141
- if (typeof discriminatorVal === 'string' && discriminators[discriminatorVal] != null) {
142
- schematype = discriminators[discriminatorVal].path(pathLastHalf);
142
+ const discriminator = typeof discriminatorVal === 'string' ? getDiscriminatorByKey(discriminators, discriminatorVal) : null;
143
+ if (discriminator != null) {
144
+ schematype = discriminator.path(pathLastHalf);
143
145
  }
144
146
  }
145
147
  }
package/lib/connection.js CHANGED
@@ -565,8 +565,8 @@ Connection.prototype.bulkWrite = async function bulkWrite(ops, options) {
565
565
  );
566
566
  }
567
567
  const BulkWriteResult = this.base.driver.get().BulkWriteResult;
568
- const res = new BulkWriteResult(getDefaultBulkwriteResult(), false);
569
- return decorateBulkWriteResult(res, validationErrors, results);
568
+ const bulkWriteResult = new BulkWriteResult(getDefaultBulkwriteResult(), false);
569
+ return decorateBulkWriteResult(bulkWriteResult, validationErrors, results);
570
570
  }
571
571
 
572
572
  let error;
@@ -578,11 +578,16 @@ Connection.prototype.bulkWrite = async function bulkWrite(ops, options) {
578
578
  results[validOpIndexes[i]] = null;
579
579
  }
580
580
  if (error) {
581
+ // client.bulkWrite() writeErrors is a Map keyed by index in validOps
582
+ error.writeErrors?.forEach((writeError, i) => {
583
+ results[validOpIndexes[i]] = writeError;
584
+ });
581
585
  if (validationErrors.length > 0) {
582
586
  decorateBulkWriteResult(error, validationErrors, results);
583
587
  error.mongoose = error.mongoose || {};
584
588
  error.mongoose.validationErrors = validationErrors;
585
589
  }
590
+ throw error;
586
591
  }
587
592
 
588
593
  if (validationErrors.length > 0) {
@@ -661,7 +666,7 @@ Connection.prototype.withSession = async function withSession(executor) {
661
666
  };
662
667
 
663
668
  /**
664
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
669
+ * Starts a [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
665
670
  * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
666
671
  * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
667
672
  *
@@ -696,7 +701,7 @@ Connection.prototype.startSession = async function startSession(options) {
696
701
  };
697
702
 
698
703
  /**
699
- * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
704
+ * Executes the wrapped async function
700
705
  * in a transaction. Mongoose will commit the transaction if the
701
706
  * async function executes successfully and attempt to retry if
702
707
  * there was a retriable error.
package/lib/document.js CHANGED
@@ -792,7 +792,11 @@ function init(self, obj, doc, opts, prefix) {
792
792
  }
793
793
 
794
794
  if (!schemaType && utils.isPOJO(value)) {
795
- // assume nested object
795
+ // assume nested object. Skip inherited properties like `Object.prototype.toString`
796
+ // to avoid setting properties on shared objects
797
+ if (!Object.hasOwn(doc, i) && i in doc) {
798
+ continue;
799
+ }
796
800
  if (!doc[i]) {
797
801
  doc[i] = {};
798
802
  if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
@@ -1811,6 +1815,12 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1811
1815
  } else {
1812
1816
  const isMap = obj instanceof Map;
1813
1817
  let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
1818
+ // Skip inherited properties like `Object.prototype.toString`, document methods,
1819
+ // or document internals like `$__schema` to avoid setting properties on shared
1820
+ // objects. Document properties are getters on the prototype, so check `_doc`.
1821
+ if (!isMap && !Object.hasOwn(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1822
+ return;
1823
+ }
1814
1824
  if (utils.isPOJO(value)) {
1815
1825
  obj = value;
1816
1826
  } else if (value && value instanceof Embedded) {
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const getDiscriminatorByKey = require('./getDiscriminatorByKey');
3
4
  const getDiscriminatorByValue = require('./getDiscriminatorByValue');
4
5
 
5
6
  /**
@@ -15,8 +16,9 @@ module.exports = function getConstructor(Constructor, value, defaultDiscriminato
15
16
  }
16
17
  if (Constructor.discriminators &&
17
18
  discriminatorValue != null) {
18
- if (Constructor.discriminators[discriminatorValue]) {
19
- Constructor = Constructor.discriminators[discriminatorValue];
19
+ const discriminator = getDiscriminatorByKey(Constructor.discriminators, discriminatorValue);
20
+ if (discriminator) {
21
+ Constructor = discriminator;
20
22
  } else {
21
23
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, discriminatorValue);
22
24
  if (constructorByValue) {
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Returns the discriminator registered under `key`, ignoring inherited properties
5
+ * like `constructor` or `toString`, because `key` may come from user data.
6
+ *
7
+ * @param {object} discriminators
8
+ * @param {string} key
9
+ * @api private
10
+ */
11
+
12
+ module.exports = function getDiscriminatorByKey(discriminators, key) {
13
+ if (discriminators == null || key == null) {
14
+ return null;
15
+ }
16
+ return Object.hasOwn(discriminators, key) ? discriminators[key] : null;
17
+ };
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
3
4
  const get = require('../get');
4
5
  const getSchemaDiscriminatorByValue = require('../discriminator/getSchemaDiscriminatorByValue');
5
6
 
@@ -40,7 +41,7 @@ module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) {
40
41
  const discriminators = schemaType.schema.discriminators;
41
42
  const discriminatorKey = doc.get(subpath + '.' +
42
43
  get(schemaType, 'schema.options.discriminatorKey'));
43
- if (discriminatorKey == null || discriminators[discriminatorKey] == null) {
44
+ if (discriminatorKey == null || getDiscriminatorByKey(discriminators, discriminatorKey) == null) {
44
45
  continue;
45
46
  }
46
47
  const rest = parts.slice(i + 1).join('.');
@@ -20,6 +20,11 @@ module.exports = function setDottedPath(obj, path, val) {
20
20
  if (specialProperties.has(part)) {
21
21
  continue;
22
22
  }
23
+ // Skip inherited properties like `Object.prototype.toString` to avoid
24
+ // setting properties on shared objects
25
+ if (!Object.hasOwn(cur, part) && part in cur) {
26
+ return;
27
+ }
23
28
  if (cur[part] == null) {
24
29
  cur[part] = {};
25
30
  }
@@ -4,6 +4,7 @@ const MongooseError = require('../../error/index');
4
4
  const SkipPopulateValue = require('./skipPopulateValue');
5
5
  const clone = require('../clone');
6
6
  const get = require('../get');
7
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
7
8
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
8
9
  const getConstructorName = require('../getConstructorName');
9
10
  const getSchemaTypes = require('./getSchemaTypes');
@@ -846,7 +847,7 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
846
847
  modelNames = [];
847
848
  for (const subdoc of subdocs) {
848
849
  const discriminatorName = utils.getValue(discriminatorKey, subdoc);
849
- const discriminator = schematype.Constructor.discriminators[discriminatorName];
850
+ const discriminator = getDiscriminatorByKey(schematype.Constructor.discriminators, discriminatorName);
850
851
  const discriminatorSchema = discriminator?.schema;
851
852
  if (discriminatorSchema == null) {
852
853
  continue;
@@ -6,7 +6,7 @@ const MongooseError = require('../error/index');
6
6
  function processConnectionOptions(uri, options) {
7
7
  const opts = options ? options : {};
8
8
  const readPreference = opts.readPreference
9
- ? opts.readPreference
9
+ ? getReadPreferenceMode(opts.readPreference)
10
10
  : getUriReadPreference(uri);
11
11
 
12
12
  const clonedOpts = clone(opts);
@@ -40,6 +40,11 @@ function setsSecondaryRead(prefString) {
40
40
  return !!(prefString === 'secondary' || prefString === 'secondaryPreferred');
41
41
  }
42
42
 
43
+ function getReadPreferenceMode(readPreference) {
44
+ // the MongoDB driver also accepts a `ReadPreference` instance or a `{ mode }` object
45
+ return typeof readPreference === 'string' ? readPreference : readPreference.mode;
46
+ }
47
+
43
48
  function getUriReadPreference(connectionString) {
44
49
  const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/;
45
50
  const match = exp.exec(connectionString);
@@ -8,6 +8,7 @@ const ValidationError = require('../../error/validation');
8
8
  const castNumber = require('../../cast/number');
9
9
  const cast = require('../../cast');
10
10
  const getConstructorName = require('../getConstructorName');
11
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
11
12
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
12
13
  const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
13
14
  const handleImmutable = require('./handleImmutable');
@@ -71,7 +72,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
71
72
  schema.discriminators != null) {
72
73
  const discriminatorValue = filter[schema.options.discriminatorKey];
73
74
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
74
- schema = schema.discriminators[discriminatorValue] ||
75
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
75
76
  byValue?.schema ||
76
77
  schema;
77
78
  } else if (schema != null &&
@@ -80,7 +81,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
80
81
  schema.discriminators != null) {
81
82
  const discriminatorValue = obj[schema.options.discriminatorKey];
82
83
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
83
- schema = schema.discriminators[discriminatorValue] ||
84
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
84
85
  byValue?.schema ||
85
86
  schema;
86
87
  } else if (schema != null &&
@@ -90,12 +91,12 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
90
91
  schema.discriminators != null) {
91
92
  const discriminatorValue = obj.$set[schema.options.discriminatorKey];
92
93
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
93
- schema = schema.discriminators[discriminatorValue] ||
94
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
94
95
  byValue?.schema ||
95
96
  schema;
96
97
  }
97
98
 
98
- if (options.upsert) {
99
+ if (options.upsert && !options.overwriteImmutable) {
99
100
  moveImmutableProperties(schema, obj, context);
100
101
  }
101
102
 
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
4
+
3
5
  const numberRE = /^\d+$/;
4
6
 
5
7
  /**
@@ -30,7 +32,7 @@ module.exports = function getPath(schema, path, discriminatorValueMap) {
30
32
  isArray = true;
31
33
  }
32
34
  if (discriminatorValueMap && discriminatorValueMap[cur]) {
33
- schema = schema.discriminators[discriminatorValueMap[cur]] ?? schema;
35
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValueMap[cur]) ?? schema;
34
36
  }
35
37
  cur = '';
36
38
  } else if (schematype?.instance === 'Mixed') {
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  const utils = require('../../utils');
8
+ const get = require('../get');
8
9
 
9
10
  module.exports = applyTimestampsToUpdate;
10
11
 
@@ -81,9 +82,9 @@ function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, optio
81
82
 
82
83
  if (!skipCreatedAt && createdAt) {
83
84
  const overwriteImmutable = options?.overwriteImmutable;
84
- const hasUserCreatedAt = currentUpdate[createdAt] != null
85
- || currentUpdate.$set?.[createdAt] != null
86
- || currentUpdate.$setOnInsert?.[createdAt] != null;
85
+ const hasUserCreatedAt = get(currentUpdate, createdAt) != null
86
+ || get(currentUpdate.$set, createdAt) != null
87
+ || get(currentUpdate.$setOnInsert, createdAt) != null;
87
88
 
88
89
  // If overwriteImmutable is true and user provided createdAt, keep their value
89
90
  if (overwriteImmutable && hasUserCreatedAt) {
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
3
4
  const castFilterPath = require('../query/castFilterPath');
4
5
  const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
5
6
  const getPath = require('../schema/getPath');
@@ -89,7 +90,7 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
89
90
  let filterBaseSchema = baseSchematype != null ? baseSchematype.schema : null;
90
91
  if (filterBaseSchema?.discriminators != null &&
91
92
  filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) {
92
- filterBaseSchema = filterBaseSchema.discriminators[filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]] || filterBaseSchema;
93
+ filterBaseSchema = getDiscriminatorByKey(filterBaseSchema.discriminators, filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) || filterBaseSchema;
93
94
  discriminatorValueMap[baseFilterPath] = filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey];
94
95
  }
95
96
 
package/lib/model.js CHANGED
@@ -50,6 +50,7 @@ const discriminator = require('./helpers/model/discriminator');
50
50
  const each = require('./helpers/each');
51
51
  const get = require('./helpers/get');
52
52
  const getConstructorName = require('./helpers/getConstructorName');
53
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
53
54
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
54
55
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
55
56
  const immediate = require('./helpers/immediate');
@@ -1321,7 +1322,7 @@ Model.createCollection = async function createCollection(options) {
1321
1322
  * toCreate; // Array of strings containing names of indexes that `syncIndexes()` will create
1322
1323
  *
1323
1324
  * @param {object} [options] options to pass to `ensureIndexes()`
1324
- * @param {boolean} [options.hideIndexes=false] set to `true` to hide indexes instead of dropping. Requires MongoDB server 4.4 or higher
1325
+ * @param {boolean} [options.hideIndexes=false] set to `true` to hide indexes instead of dropping
1325
1326
  * @return {Promise}
1326
1327
  * @api public
1327
1328
  */
@@ -1562,7 +1563,7 @@ function getIndexesToDrop(schema, schemaIndexes, dbIndexes) {
1562
1563
  *
1563
1564
  * @param {object} [options]
1564
1565
  * @param {string[]} [options.toDrop] if specified, contains a list of index names to drop
1565
- * @param {boolean} [options.hideIndexes=false] set to `true` to hide indexes instead of dropping. Requires MongoDB server 4.4 or higher
1566
+ * @param {boolean} [options.hideIndexes=false] set to `true` to hide indexes instead of dropping
1566
1567
  * @return {Promise<string[]>} list of dropped or hidden index names
1567
1568
  * @api public
1568
1569
  */
@@ -2454,7 +2455,7 @@ Model.$where = function $where() {
2454
2455
  * @param {object|string|string[]} [options.projection=null] optional fields to return, see [`Query.prototype.select()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.select())
2455
2456
  * @param {boolean} [options.new=false] if true, return the modified document rather than the original
2456
2457
  * @param {object|string} [options.fields] Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
2457
- * @param {number} [options.maxTimeMS] puts a time limit on the query - requires mongodb >= 2.6.0
2458
+ * @param {number} [options.maxTimeMS] puts a time limit on the query
2458
2459
  * @param {object|string} [options.sort] if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
2459
2460
  * @param {boolean} [options.runValidators] if true, runs [update validators](https://mongoosejs.com/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema
2460
2461
  * @param {boolean} [options.setDefaultsOnInsert=true] If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](https://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created
@@ -2594,7 +2595,7 @@ Model.findByIdAndUpdate = function(id, update, options) {
2594
2595
  * @param {boolean} [options.includeResultMetadata] if true, returns the full [ModifyResult from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/ModifyResult.html) rather than just the document
2595
2596
  * @param {object|string} [options.sort] if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
2596
2597
  * @param {object|string} [options.select] sets the document fields to return.
2597
- * @param {number} [options.maxTimeMS] puts a time limit on the query - requires mongodb >= 2.6.0
2598
+ * @param {number} [options.maxTimeMS] puts a time limit on the query
2598
2599
  * @param {boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.
2599
2600
  * @return {Query}
2600
2601
  * @api public
@@ -2674,7 +2675,7 @@ Model.findByIdAndDelete = function(id, options) {
2674
2675
  * @param {object|string} [options.sort] if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
2675
2676
  * @param {boolean} [options.includeResultMetadata] if true, returns the full [ModifyResult from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/ModifyResult.html) rather than just the document
2676
2677
  * @param {object|string} [options.select] sets the document fields to return.
2677
- * @param {number} [options.maxTimeMS] puts a time limit on the query - requires mongodb >= 2.6.0
2678
+ * @param {number} [options.maxTimeMS] puts a time limit on the query
2678
2679
  * @param {boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.
2679
2680
  * @return {Query}
2680
2681
  * @api public
@@ -2793,7 +2794,7 @@ Model.create = async function create(doc, options) {
2793
2794
  let toSave = doc;
2794
2795
 
2795
2796
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2796
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2797
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2797
2798
  this;
2798
2799
  if (Model == null) {
2799
2800
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2814,7 +2815,7 @@ Model.create = async function create(doc, options) {
2814
2815
  try {
2815
2816
  const doc = args[i];
2816
2817
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2817
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2818
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2818
2819
  this;
2819
2820
  if (Model == null) {
2820
2821
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2839,7 +2840,7 @@ Model.create = async function create(doc, options) {
2839
2840
  } else if (!immediateError) {
2840
2841
  res = await Promise.allSettled(args.map(async doc => {
2841
2842
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2842
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2843
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2843
2844
  this;
2844
2845
  if (Model == null) {
2845
2846
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2860,7 +2861,7 @@ Model.create = async function create(doc, options) {
2860
2861
  let firstError = null;
2861
2862
  res = await Promise.all(args.map(async doc => {
2862
2863
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2863
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2864
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2864
2865
  this;
2865
2866
  if (Model == null) {
2866
2867
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2923,7 +2924,7 @@ Model.insertOne = async function insertOne(doc, options) {
2923
2924
 
2924
2925
  const discriminatorKey = this.schema.options.discriminatorKey;
2925
2926
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2926
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2927
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2927
2928
  this;
2928
2929
  if (Model == null) {
2929
2930
  throw new MongooseError(
@@ -2938,8 +2939,7 @@ Model.insertOne = async function insertOne(doc, options) {
2938
2939
  };
2939
2940
 
2940
2941
  /**
2941
- * _Requires a replica set running MongoDB >= 3.6.0._ Watches the
2942
- * underlying collection for changes using
2942
+ * Watches the underlying collection for changes using
2943
2943
  * [MongoDB change streams](https://www.mongodb.com/docs/manual/changeStreams/).
2944
2944
  *
2945
2945
  * This function does **not** trigger any middleware. In particular, it
@@ -2991,7 +2991,7 @@ Model.watch = function(pipeline, options) {
2991
2991
  };
2992
2992
 
2993
2993
  /**
2994
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
2994
+ * Starts a [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
2995
2995
  * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
2996
2996
  * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
2997
2997
  *
@@ -4431,12 +4431,6 @@ Model.validate = async function validate(obj, pathsOrOptions, context) {
4431
4431
  continue;
4432
4432
  }
4433
4433
 
4434
- const pieces = path.indexOf('.') === -1 ? [path] : path.split('.');
4435
- let cur = obj;
4436
- for (let i = 0; i < pieces.length - 1; ++i) {
4437
- cur = cur[pieces[i]];
4438
- }
4439
-
4440
4434
  const val = get(obj, path, void 0);
4441
4435
  promises.push(
4442
4436
  schemaType.doValidate(val, context, { path: path }).catch(err => {
@@ -5077,7 +5071,7 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
5077
5071
  }
5078
5072
 
5079
5073
  // If discriminator key is set, use the discriminator instead (gh-7586)
5080
- const Discriminator = model.discriminators[doc[discriminatorKey]] ||
5074
+ const Discriminator = getDiscriminatorByKey(model.discriminators, doc[discriminatorKey]) ||
5081
5075
  getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
5082
5076
  if (Discriminator != null) {
5083
5077
  return new Discriminator(doc, fields, skipId);
package/lib/mongoose.js CHANGED
@@ -497,7 +497,7 @@ Mongoose.prototype.disconnect = async function disconnect() {
497
497
  };
498
498
 
499
499
  /**
500
- * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
500
+ * Starts a [MongoDB session](https://www.mongodb.com/docs/manual/reference/server-sessions/)
501
501
  * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
502
502
  * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
503
503
  *
package/lib/query.js CHANGED
@@ -239,8 +239,6 @@ Object.defineProperty(Query.prototype, '_distinct', {
239
239
  * mongoose.Query.use$geoWithin = false;
240
240
  * ```
241
241
  *
242
- * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work.
243
- *
244
242
  * @see geoWithin https://www.mongodb.com/docs/manual/reference/operator/geoWithin/
245
243
  * @default true
246
244
  * @property use$geoWithin
@@ -434,6 +432,14 @@ Query.prototype.clone = function() {
434
432
  * @api public
435
433
  */
436
434
 
435
+ Query.prototype.where = function where(path) {
436
+ if (typeof path === 'string' && specialProperties.has(path)) {
437
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
438
+ }
439
+
440
+ return Query.base.where.apply(this, arguments);
441
+ };
442
+
437
443
  /**
438
444
  * Specifies a `$slice` projection for an array.
439
445
  *
@@ -814,7 +820,13 @@ Query.prototype.mod = function() {
814
820
  path = arguments[0];
815
821
  }
816
822
 
817
- const conds = this._conditions[path] || (this._conditions[path] = {});
823
+ if (path != null && specialProperties.has(String(path))) {
824
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
825
+ }
826
+
827
+ // Avoid reusing inherited properties like `toString`
828
+ const conds = (Object.hasOwn(this._conditions, path) && this._conditions[path]) ||
829
+ (this._conditions[path] = {});
818
830
  conds.$mod = val;
819
831
  return this;
820
832
  };
@@ -1620,11 +1632,11 @@ Query.prototype.wtimeout = function wtimeout(ms) {
1620
1632
  * #### Read Concern Level:
1621
1633
  *
1622
1634
  * ```
1623
- * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1624
- * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1625
- * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
1626
- * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
1627
- * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
1635
+ * local The query returns from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1636
+ * available The query returns from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
1637
+ * majority The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
1638
+ * linearizable The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
1639
+ * snapshot Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.
1628
1640
  * ```
1629
1641
  *
1630
1642
  * Aliases
@@ -1879,9 +1891,6 @@ Query.prototype.explain = function explain(verbose) {
1879
1891
  * which allows the MongoDB server to use more than 100 MB for this query's `sort()`. This option can
1880
1892
  * let you work around `QueryExceededMemoryLimitNoDiskUseAllowed` errors from the MongoDB server.
1881
1893
  *
1882
- * Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2
1883
- * and earlier.
1884
- *
1885
1894
  * Calling `query.allowDiskUse(v)` is equivalent to `query.setOptions({ allowDiskUse: v })`
1886
1895
  *
1887
1896
  * #### Example:
@@ -2410,14 +2419,10 @@ Query.prototype.mongooseOptions = function(v) {
2410
2419
  */
2411
2420
 
2412
2421
  Query.prototype._castConditions = function() {
2413
- let sanitizeFilterOpt = undefined;
2414
- if (this.model?.db.options?.sanitizeFilter != null) {
2415
- sanitizeFilterOpt = this.model.db.options.sanitizeFilter;
2416
- } else if (this.model?.base.options?.sanitizeFilter != null) {
2417
- sanitizeFilterOpt = this.model.base.options.sanitizeFilter;
2418
- } else {
2419
- sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter;
2420
- }
2422
+ const sanitizeFilterOpt = this.model?.db.config?.sanitizeFilter ??
2423
+ this.model?.db.options?.sanitizeFilter ??
2424
+ this.model?.base.options.sanitizeFilter ??
2425
+ this._mongooseOptions.sanitizeFilter;
2421
2426
 
2422
2427
  if (sanitizeFilterOpt) {
2423
2428
  sanitizeFilter(this._conditions);
@@ -2687,7 +2692,7 @@ Query.prototype.merge = function(source) {
2687
2692
  };
2688
2693
 
2689
2694
  /**
2690
- * Adds a collation to this op (MongoDB 3.4 and up)
2695
+ * Adds a collation to this op.
2691
2696
  *
2692
2697
  * @param {object} value
2693
2698
  * @return {Query} this
@@ -3469,7 +3474,7 @@ function prepareDiscriminatorCriteria(query) {
3469
3474
  * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
3470
3475
  * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
3471
3476
  * - `sort`: if multiple docs are found by the filter, sets the sort order to choose which doc to update
3472
- * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
3477
+ * - `maxTimeMS`: puts a time limit on the query
3473
3478
  * - `runValidators`: if true, runs [update validators](https://mongoosejs.com/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
3474
3479
  * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](https://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created.
3475
3480
  * - `requireFilter`: bool - if true, throws an error if the filter is empty (`{}`). Defaults to false.
@@ -3685,7 +3690,7 @@ Query.prototype._findOneAndUpdate = async function _findOneAndUpdate() {
3685
3690
  * #### Available options
3686
3691
  *
3687
3692
  * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
3688
- * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
3693
+ * - `maxTimeMS`: puts a time limit on the query
3689
3694
  * - `requireFilter`: bool - if true, throws an error if the filter is empty (`{}`). Defaults to false.
3690
3695
  *
3691
3696
  * #### Example:
@@ -3778,7 +3783,7 @@ Query.prototype._findOneAndDelete = async function _findOneAndDelete() {
3778
3783
  * #### Available options
3779
3784
  *
3780
3785
  * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
3781
- * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
3786
+ * - `maxTimeMS`: puts a time limit on the query
3782
3787
  * - `includeResultMetadata`: if true, returns the full [ModifyResult from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/ModifyResult.html) rather than just the document
3783
3788
  * - `requireFilter`: bool - if true, throws an error if the filter is empty (`{}`). Defaults to false.
3784
3789
  *
@@ -5248,9 +5253,10 @@ Query.prototype.cast = function(model, obj) {
5248
5253
  if ('strictQuery' in this._mongooseOptions) {
5249
5254
  opts.strictQuery = this._mongooseOptions.strictQuery;
5250
5255
  }
5251
- if ('sanitizeFilter' in this._mongooseOptions) {
5252
- opts.sanitizeFilter = this._mongooseOptions.sanitizeFilter;
5253
- }
5256
+ opts.sanitizeFilter = model.db.config?.sanitizeFilter ??
5257
+ model.db.options?.sanitizeFilter ??
5258
+ model.base.options.sanitizeFilter ??
5259
+ this._mongooseOptions.sanitizeFilter;
5254
5260
 
5255
5261
  try {
5256
5262
  return cast(model.schema, obj, opts, this);
@@ -5542,7 +5548,6 @@ Query.prototype.tailable = function(val, opts) {
5542
5548
  * @param {object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples.
5543
5549
  * @return {Query} this
5544
5550
  * @see $geometry https://www.mongodb.com/docs/manual/reference/operator/geometry/
5545
- * @see Geospatial Support Enhancements https://www.mongodb.com/docs/manual/release-notes/2.4/#geospatial-support-enhancements
5546
5551
  * @see MongoDB Geospatial Indexing https://www.mongodb.com/docs/manual/core/geospatial-indexes/
5547
5552
  * @api public
5548
5553
  */
@@ -4,6 +4,7 @@
4
4
  * Module dependencies
5
5
  */
6
6
 
7
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
7
8
  const PopulateOptions = require('./options/populateOptions');
8
9
  const checkEmbeddedDiscriminatorKeyProjection =
9
10
  require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection');
@@ -98,7 +99,7 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
98
99
 
99
100
  const value = doc[key];
100
101
  if (key && value && model.discriminators) {
101
- const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
102
+ const discriminator = getDiscriminatorByKey(model.discriminators, value) || getDiscriminatorByValue(model.discriminators, value);
102
103
  if (discriminator) {
103
104
  const _fields = clone(userProvidedFields);
104
105
  exports.applyPaths(_fields, discriminator.schema);
@@ -22,6 +22,7 @@ const util = require('util');
22
22
  const utils = require('../utils');
23
23
  const castToNumber = require('./operators/helpers').castToNumber;
24
24
  const geospatial = require('./operators/geospatial');
25
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
25
26
  const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
26
27
 
27
28
  let MongooseArray;
@@ -507,8 +508,9 @@ SchemaArray.prototype._castForQuery = function(val, context) {
507
508
  const discriminators = embeddedSchemaType?.discriminators;
508
509
 
509
510
  if (val && discriminators && typeof discriminatorKey === 'string') {
510
- if (discriminators[val[discriminatorKey]]) {
511
- embeddedSchemaType = discriminators[val[discriminatorKey]];
511
+ const discriminator = getDiscriminatorByKey(discriminators, val[discriminatorKey]);
512
+ if (discriminator) {
513
+ embeddedSchemaType = discriminator;
512
514
  } else {
513
515
  const constructorByValue = getDiscriminatorByValue(discriminators, val[discriminatorKey]);
514
516
  if (constructorByValue) {
@@ -143,7 +143,7 @@ SchemaDate._defaultCaster = v => {
143
143
  /**
144
144
  * Declares a TTL index (rounded to the nearest second) for _Date_ types only.
145
145
  *
146
- * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2.
146
+ * This sets the `expireAfterSeconds` index option.
147
147
  * This index type is only compatible with Date types.
148
148
  *
149
149
  * #### Example:
@@ -4,6 +4,7 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
7
8
  const CastError = require('../error/cast');
8
9
  const DocumentArrayElement = require('./documentArrayElement');
9
10
  const EventEmitter = require('events').EventEmitter;
@@ -652,10 +653,11 @@ function cast$elemMatch(val, context) {
652
653
  // If so, use the discriminator schema. See gh-7449
653
654
  const discriminatorKey = this?.Constructor?.schema?.options?.discriminatorKey;
654
655
  const discriminators = this?.Constructor?.schema?.discriminators || {};
655
- if (discriminatorKey != null &&
656
- val[discriminatorKey] != null &&
657
- discriminators[val[discriminatorKey]] != null) {
658
- return cast(discriminators[val[discriminatorKey]], val, null, this?.$$context);
656
+ const discriminator = discriminatorKey != null && val[discriminatorKey] != null ?
657
+ getDiscriminatorByKey(discriminators, val[discriminatorKey]) :
658
+ null;
659
+ if (discriminator != null) {
660
+ return cast(discriminator, val, null, this?.$$context);
659
661
  }
660
662
 
661
663
  const schema = this.Constructor.schema ?? context.schema;
package/lib/schema.js CHANGED
@@ -2653,6 +2653,12 @@ Schema.prototype.virtual = function(name, options) {
2653
2653
  if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2654
2654
  return this.virtual(name.path, name.options);
2655
2655
  }
2656
+ const parts = name.split('.');
2657
+ for (const part of parts) {
2658
+ if (utils.specialProperties.has(part)) {
2659
+ throw new MongooseError('Cannot set special property `' + part + '` on a schema');
2660
+ }
2661
+ }
2656
2662
  options = new VirtualOptions(options);
2657
2663
 
2658
2664
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
@@ -2754,7 +2760,6 @@ Schema.prototype.virtual = function(name, options) {
2754
2760
  }
2755
2761
 
2756
2762
  const virtuals = this.virtuals;
2757
- const parts = name.split('.');
2758
2763
 
2759
2764
  if (this.pathType(name) === 'real') {
2760
2765
  throw new MongooseError('Virtual path "' + name + '"' +
@@ -2,6 +2,7 @@
2
2
 
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
+ const getDiscriminatorByKey = require('../../../helpers/discriminator/getDiscriminatorByKey');
5
6
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
6
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
7
8
  const utils = require('../../../utils');
@@ -93,9 +94,11 @@ const methods = {
93
94
  Constructor.schema &&
94
95
  Constructor.schema.options &&
95
96
  Constructor.schema.options.discriminatorKey) {
96
- if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
97
- Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
98
- Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
97
+ const discriminator = typeof value[Constructor.schema.options.discriminatorKey] === 'string' ?
98
+ getDiscriminatorByKey(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]) :
99
+ null;
100
+ if (discriminator) {
101
+ Constructor = discriminator;
99
102
  } else {
100
103
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
101
104
  if (constructorByValue) {
@@ -414,9 +417,11 @@ const methods = {
414
417
  Constructor.schema &&
415
418
  Constructor.schema.options &&
416
419
  Constructor.schema.options.discriminatorKey) {
417
- if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
418
- Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
419
- Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
420
+ const discriminator = typeof obj[Constructor.schema.options.discriminatorKey] === 'string' ?
421
+ getDiscriminatorByKey(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]) :
422
+ null;
423
+ if (discriminator) {
424
+ Constructor = discriminator;
420
425
  } else {
421
426
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
422
427
  if (constructorByValue) {
package/lib/utils.js CHANGED
@@ -926,6 +926,12 @@ exports.mergeClone = function(to, fromObj) {
926
926
  if (specialProperties.has(key)) {
927
927
  continue;
928
928
  }
929
+ // Skip inherited properties like `Object.prototype.toString` to avoid setting
930
+ // properties on shared objects. Document properties are getters on the
931
+ // prototype, so check `_doc`.
932
+ if (!Object.hasOwn(to.$__ == null ? to : to._doc, key) && key in to) {
933
+ continue;
934
+ }
929
935
  if (typeof to[key] === 'undefined') {
930
936
  to[key] = clone(fromObj[key], {
931
937
  transform: false,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "9.11.2",
4
+ "version": "9.11.4",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -24,7 +24,7 @@
24
24
  "kareem": "3.4.1",
25
25
  "mongodb": "~7.7",
26
26
  "mpath": "0.9.0",
27
- "mquery": "6.0.0",
27
+ "mquery": "6.0.1",
28
28
  "ms": "2.1.3",
29
29
  "sift": "17.1.3"
30
30
  },