mongoose 8.24.5 → 8.24.7

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.
@@ -30,6 +30,12 @@ module.exports = function castDouble(val) {
30
30
  assert.ok(false);
31
31
  }
32
32
  } else if (typeof val === 'object') {
33
+ if (Array.isArray(val)) {
34
+ // `[5].valueOf()` returns the array itself, so without this guard a
35
+ // single-element or empty array would fall through to `Number(tempVal)`
36
+ // below and silently coerce instead of throwing.
37
+ assert.ok(false);
38
+ }
33
39
  const tempVal = val.valueOf() ?? val.toString();
34
40
  // ex: { a: 'im an object, valueOf: () => 'helloworld' } // throw an error
35
41
  if (typeof tempVal === 'string') {
package/lib/cast/int32.js CHANGED
@@ -20,6 +20,12 @@ module.exports = function castInt32(val) {
20
20
  if (val === '') {
21
21
  return null;
22
22
  }
23
+ if (Array.isArray(val)) {
24
+ // `Number([5])` is `5` and `Number([])` is `0`, so without this guard a
25
+ // single-element or empty array would silently coerce instead of throwing,
26
+ // unlike every other array input and unlike `castNumber()`'s own guard.
27
+ assert.ok(false);
28
+ }
23
29
 
24
30
  const coercedVal = isBsonType(val, 'Long') ? val.toNumber() : Number(val);
25
31
 
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');
@@ -140,16 +141,18 @@ module.exports = function cast(schema, obj, options, context) {
140
141
  pathLastHalf !== discriminatorKey) {
141
142
  const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
142
143
  const discriminators = _schematype.schema.discriminators;
143
- if (typeof discriminatorVal === 'string' && discriminators[discriminatorVal] != null) {
144
-
145
- schematype = discriminators[discriminatorVal].path(pathLastHalf);
146
- } else if (discriminatorVal != null &&
144
+ const discriminator = typeof discriminatorVal === 'string' ? getDiscriminatorByKey(discriminators, discriminatorVal) : null;
145
+ const discriminatorFromIn = discriminatorVal != null &&
147
146
  Object.keys(discriminatorVal).length === 1 &&
148
147
  Array.isArray(discriminatorVal.$in) &&
149
148
  discriminatorVal.$in.length === 1 &&
150
- typeof discriminatorVal.$in[0] === 'string' &&
151
- discriminators[discriminatorVal.$in[0]] != null) {
152
- schematype = discriminators[discriminatorVal.$in[0]].path(pathLastHalf);
149
+ typeof discriminatorVal.$in[0] === 'string' ?
150
+ getDiscriminatorByKey(discriminators, discriminatorVal.$in[0]) :
151
+ null;
152
+ if (discriminator != null) {
153
+ schematype = discriminator.path(pathLastHalf);
154
+ } else if (discriminatorFromIn != null) {
155
+ schematype = discriminatorFromIn.path(pathLastHalf);
153
156
  }
154
157
  }
155
158
  }
package/lib/document.js CHANGED
@@ -767,7 +767,11 @@ function init(self, obj, doc, opts, prefix) {
767
767
 
768
768
  const value = obj[i];
769
769
  if (!schemaType && utils.isPOJO(value)) {
770
- // assume nested object
770
+ // assume nested object. Skip inherited properties like `Object.prototype.toString`
771
+ // to avoid setting properties on shared objects
772
+ if (!Object.hasOwn(doc, i) && i in doc) {
773
+ continue;
774
+ }
771
775
  if (!doc[i]) {
772
776
  doc[i] = {};
773
777
  if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
@@ -1762,6 +1766,12 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1762
1766
  } else {
1763
1767
  const isMap = obj instanceof Map;
1764
1768
  let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
1769
+ // Skip inherited properties like `Object.prototype.toString`, document methods,
1770
+ // or document internals like `$__schema` to avoid setting properties on shared
1771
+ // objects. Document properties are getters on the prototype, so check `_doc`.
1772
+ if (!isMap && !Object.hasOwn(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1773
+ return;
1774
+ }
1765
1775
  if (utils.isPOJO(value)) {
1766
1776
  obj = value;
1767
1777
  } else if (value && value instanceof Embedded) {
@@ -197,6 +197,11 @@ function cloneObject(obj, options, isArrayChild) {
197
197
  }
198
198
 
199
199
  function cloneArray(arr, options) {
200
+ const seen = options?._seen;
201
+ if (seen && seen.has(arr)) {
202
+ return seen.get(arr);
203
+ }
204
+
200
205
  let i = 0;
201
206
  const len = arr.length;
202
207
 
@@ -218,6 +223,10 @@ function cloneArray(arr, options) {
218
223
  ret = new Array(len);
219
224
  }
220
225
 
226
+ if (seen) {
227
+ seen.set(arr, ret);
228
+ }
229
+
221
230
  arr = isMongooseArray(arr) ? arr.__array : arr;
222
231
  if (ret.isMongooseDocumentArray) {
223
232
  // Create new options object to avoid mutating the shared options.
@@ -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('.');
@@ -178,13 +178,15 @@ module.exports.castUpdateMany = function castUpdateMany(originalModel, updateMan
178
178
  const schema = model.schema;
179
179
  const strict = options.strict != null ? options.strict : model.schema.options.strict;
180
180
 
181
+ const update = clone(updateMany['update']);
182
+
181
183
  const globalSetDefaultsOnInsert = originalModel.base.options.setDefaultsOnInsert;
182
184
  const shouldSetDefaultsOnInsert = updateMany.setDefaultsOnInsert == null ?
183
185
  globalSetDefaultsOnInsert :
184
186
  updateMany.setDefaultsOnInsert;
185
187
 
186
188
  if (shouldSetDefaultsOnInsert !== false) {
187
- setDefaultsOnInsert(updateMany['filter'], model.schema, updateMany['update'], {
189
+ setDefaultsOnInsert(updateMany['filter'], model.schema, update, {
188
190
  setDefaultsOnInsert: true,
189
191
  upsert: updateMany.upsert
190
192
  });
@@ -195,19 +197,19 @@ module.exports.castUpdateMany = function castUpdateMany(originalModel, updateMan
195
197
  if (model.schema.$timestamps != null && doInitTimestamps) {
196
198
  const createdAt = model.schema.$timestamps.createdAt;
197
199
  const updatedAt = model.schema.$timestamps.updatedAt;
198
- applyTimestampsToUpdate(now, createdAt, updatedAt, updateMany['update'], {
200
+ applyTimestampsToUpdate(now, createdAt, updatedAt, update, {
199
201
  timestamps: updateMany.timestamps,
200
202
  overwriteImmutable: updateMany.overwriteImmutable
201
203
  });
202
204
  }
203
205
  if (doInitTimestamps) {
204
- applyTimestampsToChildren(now, updateMany['update'], model.schema);
206
+ applyTimestampsToChildren(now, update, model.schema);
205
207
  }
206
208
 
207
209
  _addDiscriminatorToObject(schema, updateMany['filter']);
208
210
 
209
211
  decorateUpdateWithVersionKey(
210
- updateMany['update'],
212
+ update,
211
213
  updateMany,
212
214
  model.schema.options.versionKey
213
215
  );
@@ -217,7 +219,7 @@ module.exports.castUpdateMany = function castUpdateMany(originalModel, updateMan
217
219
  upsert: updateMany.upsert
218
220
  });
219
221
 
220
- updateMany['update'] = castUpdate(model.schema, updateMany['update'], {
222
+ updateMany['update'] = castUpdate(model.schema, update, {
221
223
  strict: strict,
222
224
  upsert: updateMany.upsert,
223
225
  arrayFilters: updateMany.arrayFilters,
@@ -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');
@@ -720,7 +721,7 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
720
721
  modelNames = [];
721
722
  for (const subdoc of subdocs) {
722
723
  const discriminatorName = utils.getValue(discriminatorKey, subdoc);
723
- const discriminator = schematype.caster.discriminators[discriminatorName];
724
+ const discriminator = getDiscriminatorByKey(schematype.caster.discriminators, discriminatorName);
724
725
  const discriminatorSchema = discriminator && discriminator.schema;
725
726
  if (discriminatorSchema == null) {
726
727
  continue;
@@ -7,19 +7,9 @@
7
7
  module.exports = function isPathSelectedInclusive(fields, path) {
8
8
  const chunks = path.split('.');
9
9
  let cur = '';
10
- let j;
11
- let keys;
12
- let numKeys;
13
10
  for (let i = 0; i < chunks.length; ++i) {
14
- cur += cur.length ? '.' : '' + chunks[i];
11
+ cur += cur.length ? '.' + chunks[i] : chunks[i];
15
12
  if (fields[cur]) {
16
- keys = Object.keys(fields);
17
- numKeys = keys.length;
18
- for (j = 0; j < numKeys; ++j) {
19
- if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) {
20
- continue;
21
- }
22
- }
23
13
  return true;
24
14
  }
25
15
  }
@@ -266,7 +266,7 @@ function castComparison(val, schema, strictQuery) {
266
266
  throw new StrictModeError(path);
267
267
  }
268
268
  } else {
269
- val[1] = _castExpression(val[1]);
269
+ val[1] = _castExpression(val[1], schema, strictQuery);
270
270
  }
271
271
 
272
272
  return val;
@@ -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');
@@ -70,7 +71,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
70
71
  schema.discriminators != null) {
71
72
  const discriminatorValue = filter[schema.options.discriminatorKey];
72
73
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
73
- schema = schema.discriminators[discriminatorValue] ||
74
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
74
75
  (byValue && byValue.schema) ||
75
76
  schema;
76
77
  } else if (schema != null &&
@@ -79,7 +80,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
79
80
  schema.discriminators != null) {
80
81
  const discriminatorValue = obj[schema.options.discriminatorKey];
81
82
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
82
- schema = schema.discriminators[discriminatorValue] ||
83
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
83
84
  (byValue && byValue.schema) ||
84
85
  schema;
85
86
  } else if (schema != null &&
@@ -89,7 +90,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
89
90
  schema.discriminators != null) {
90
91
  const discriminatorValue = obj.$set[schema.options.discriminatorKey];
91
92
  const byValue = getDiscriminatorByValue(context.model.discriminators, discriminatorValue);
92
- schema = schema.discriminators[discriminatorValue] ||
93
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
93
94
  (byValue && byValue.schema) ||
94
95
  schema;
95
96
  }
@@ -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') {
@@ -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');
@@ -66,7 +67,7 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
66
67
  if (filterBaseSchema != null &&
67
68
  filterBaseSchema.discriminators != null &&
68
69
  filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) {
69
- filterBaseSchema = filterBaseSchema.discriminators[filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]] || filterBaseSchema;
70
+ filterBaseSchema = getDiscriminatorByKey(filterBaseSchema.discriminators, filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) || filterBaseSchema;
70
71
  discriminatorValueMap[baseFilterPath] = filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey];
71
72
  }
72
73
 
package/lib/model.js CHANGED
@@ -44,6 +44,7 @@ const discriminator = require('./helpers/model/discriminator');
44
44
  const each = require('./helpers/each');
45
45
  const get = require('./helpers/get');
46
46
  const getConstructorName = require('./helpers/getConstructorName');
47
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
47
48
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
48
49
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
49
50
  const immediate = require('./helpers/immediate');
@@ -2732,7 +2733,7 @@ Model.create = async function create(doc, options) {
2732
2733
  try {
2733
2734
  const doc = args[i];
2734
2735
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2735
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2736
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2736
2737
  this;
2737
2738
  if (Model == null) {
2738
2739
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2757,7 +2758,7 @@ Model.create = async function create(doc, options) {
2757
2758
  } else if (!immediateError) {
2758
2759
  res = await Promise.allSettled(args.map(async doc => {
2759
2760
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2760
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2761
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2761
2762
  this;
2762
2763
  if (Model == null) {
2763
2764
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2778,7 +2779,7 @@ Model.create = async function create(doc, options) {
2778
2779
  let firstError = null;
2779
2780
  res = await Promise.all(args.map(async doc => {
2780
2781
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2781
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2782
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2782
2783
  this;
2783
2784
  if (Model == null) {
2784
2785
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2842,7 +2843,7 @@ Model.insertOne = async function insertOne(doc, options) {
2842
2843
 
2843
2844
  const discriminatorKey = this.schema.options.discriminatorKey;
2844
2845
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2845
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2846
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2846
2847
  this;
2847
2848
  if (Model == null) {
2848
2849
  throw new MongooseError(
@@ -4868,7 +4869,7 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
4868
4869
  }
4869
4870
 
4870
4871
  // If discriminator key is set, use the discriminator instead (gh-7586)
4871
- const Discriminator = model.discriminators[doc[discriminatorKey]] ||
4872
+ const Discriminator = getDiscriminatorByKey(model.discriminators, doc[discriminatorKey]) ||
4872
4873
  getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
4873
4874
  if (Discriminator != null) {
4874
4875
  return new Discriminator(doc, fields, skipId);
package/lib/query.js CHANGED
@@ -421,6 +421,14 @@ Query.prototype.clone = function() {
421
421
  * @api public
422
422
  */
423
423
 
424
+ Query.prototype.where = function where(path) {
425
+ if (typeof path === 'string' && specialProperties.has(path)) {
426
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
427
+ }
428
+
429
+ return Query.base.where.apply(this, arguments);
430
+ };
431
+
424
432
  /**
425
433
  * Specifies a `$slice` projection for an array.
426
434
  *
@@ -797,7 +805,13 @@ Query.prototype.mod = function() {
797
805
  path = arguments[0];
798
806
  }
799
807
 
800
- const conds = this._conditions[path] || (this._conditions[path] = {});
808
+ if (path != null && specialProperties.has(String(path))) {
809
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
810
+ }
811
+
812
+ // Avoid reusing inherited properties like `toString`
813
+ const conds = (Object.hasOwn(this._conditions, path) && this._conditions[path]) ||
814
+ (this._conditions[path] = {});
801
815
  conds.$mod = val;
802
816
  return this;
803
817
  };
@@ -2357,14 +2371,10 @@ Query.prototype.mongooseOptions = function(v) {
2357
2371
  */
2358
2372
 
2359
2373
  Query.prototype._castConditions = function() {
2360
- let sanitizeFilterOpt = undefined;
2361
- if (this.model?.db.options?.sanitizeFilter != null) {
2362
- sanitizeFilterOpt = this.model.db.options.sanitizeFilter;
2363
- } else if (this.model?.base.options?.sanitizeFilter != null) {
2364
- sanitizeFilterOpt = this.model.base.options.sanitizeFilter;
2365
- } else {
2366
- sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter;
2367
- }
2374
+ const sanitizeFilterOpt = this.model?.db.config?.sanitizeFilter ??
2375
+ this.model?.db.options?.sanitizeFilter ??
2376
+ this.model?.base.options.sanitizeFilter ??
2377
+ this._mongooseOptions.sanitizeFilter;
2368
2378
 
2369
2379
  if (sanitizeFilterOpt) {
2370
2380
  sanitizeFilter(this._conditions);
@@ -5047,9 +5057,10 @@ Query.prototype.cast = function(model, obj) {
5047
5057
  opts.strictQuery = this.options.strictQuery;
5048
5058
  }
5049
5059
  }
5050
- if ('sanitizeFilter' in this._mongooseOptions) {
5051
- opts.sanitizeFilter = this._mongooseOptions.sanitizeFilter;
5052
- }
5060
+ opts.sanitizeFilter = model.db.config?.sanitizeFilter ??
5061
+ model.db.options?.sanitizeFilter ??
5062
+ model.base.options.sanitizeFilter ??
5063
+ this._mongooseOptions.sanitizeFilter;
5053
5064
 
5054
5065
  try {
5055
5066
  return cast(model.schema, obj, opts, this);
@@ -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');
@@ -86,7 +87,7 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
86
87
 
87
88
  const value = doc[key];
88
89
  if (key && value && model.discriminators) {
89
- const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
90
+ const discriminator = getDiscriminatorByKey(model.discriminators, value) || getDiscriminatorByValue(model.discriminators, value);
90
91
  if (discriminator) {
91
92
  const _fields = clone(userProvidedFields);
92
93
  exports.applyPaths(_fields, discriminator.schema);
@@ -204,6 +205,13 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
204
205
  switch (exclude) {
205
206
  case true:
206
207
  for (const fieldName of excluded) {
208
+ // Skip if an ancestor path is already excluded in `fields` (for
209
+ // example the user did `.select('-subd')` and `subd.raw` has
210
+ // schema-level `select: false`) to avoid MongoDB's "Path collision"
211
+ // error from projecting both `subd` and `subd.raw`. See gh-12798
212
+ if (hasExcludedAncestor(fields, fieldName)) {
213
+ continue;
214
+ }
207
215
  fields[fieldName] = 0;
208
216
  }
209
217
  break;
@@ -370,6 +378,16 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
370
378
  (type.selected ? selected : excluded).push(path);
371
379
  return path;
372
380
  }
381
+
382
+ function hasExcludedAncestor(fields, path) {
383
+ let i = -1;
384
+ while ((i = path.indexOf('.', i + 1)) !== -1) {
385
+ if (fields[path.slice(0, i)] === 0) {
386
+ return true;
387
+ }
388
+ }
389
+ return false;
390
+ }
373
391
  };
374
392
 
375
393
  /**
@@ -23,6 +23,7 @@ const utils = require('../utils');
23
23
  const castToNumber = require('./operators/helpers').castToNumber;
24
24
  const createJSONSchemaTypeDefinition = require('../helpers/createJSONSchemaTypeDefinition');
25
25
  const geospatial = require('./operators/geospatial');
26
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
26
27
  const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
27
28
 
28
29
  let MongooseArray;
@@ -515,9 +516,11 @@ SchemaArray.prototype._castForQuery = function(val, context) {
515
516
  Constructor.schema &&
516
517
  Constructor.schema.options &&
517
518
  Constructor.schema.options.discriminatorKey) {
518
- if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
519
- Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
520
- Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
519
+ const discriminator = typeof val[Constructor.schema.options.discriminatorKey] === 'string' ?
520
+ getDiscriminatorByKey(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]) :
521
+ null;
522
+ if (discriminator) {
523
+ Constructor = discriminator;
521
524
  } else {
522
525
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]);
523
526
  if (constructorByValue) {
@@ -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;
@@ -667,10 +668,11 @@ function cast$elemMatch(val, context) {
667
668
  this.casterConstructor &&
668
669
  this.casterConstructor.schema &&
669
670
  this.casterConstructor.schema.discriminators || {};
670
- if (discriminatorKey != null &&
671
- val[discriminatorKey] != null &&
672
- discriminators[val[discriminatorKey]] != null) {
673
- return cast(discriminators[val[discriminatorKey]], val, null, this && this.$$context);
671
+ const discriminator = discriminatorKey != null && val[discriminatorKey] != null ?
672
+ getDiscriminatorByKey(discriminators, val[discriminatorKey]) :
673
+ null;
674
+ if (discriminator != null) {
675
+ return cast(discriminator, val, null, this && this.$$context);
674
676
  }
675
677
 
676
678
  const schema = this.casterConstructor.schema ?? context.schema;
package/lib/schema.js CHANGED
@@ -424,6 +424,16 @@ Schema.prototype._clone = function _clone(Constructor) {
424
424
  );
425
425
  s.nested = clone(this.nested);
426
426
  s.subpaths = clone(this.subpaths);
427
+
428
+ s.mapPaths = [];
429
+ for (const [path, schemaType] of Object.entries(s.paths)) {
430
+ const mapPath = path + '.$*';
431
+ if (!schemaType.$isSchemaMap || !Object.hasOwn(s.paths, mapPath)) {
432
+ continue;
433
+ }
434
+ s.paths[mapPath] = schemaType.$__schemaType;
435
+ s.mapPaths.push(s.paths[mapPath]);
436
+ }
427
437
  for (const schemaType of Object.values(s.paths)) {
428
438
  if (schemaType.$isSingleNested) {
429
439
  const path = schemaType.path;
@@ -451,7 +461,6 @@ Schema.prototype._clone = function _clone(Constructor) {
451
461
  s.$implicitlyCreated = this.$implicitlyCreated;
452
462
  s.$id = ++id;
453
463
  s.$originalSchemaId = this.$id;
454
- s.mapPaths = [].concat(this.mapPaths);
455
464
 
456
465
  if (this.discriminatorMapping != null) {
457
466
  s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
@@ -2502,6 +2511,12 @@ Schema.prototype.virtual = function(name, options) {
2502
2511
  if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2503
2512
  return this.virtual(name.path, name.options);
2504
2513
  }
2514
+ const parts = name.split('.');
2515
+ for (const part of parts) {
2516
+ if (utils.specialProperties.has(part)) {
2517
+ throw new MongooseError('Cannot set special property `' + part + '` on a schema');
2518
+ }
2519
+ }
2505
2520
  options = new VirtualOptions(options);
2506
2521
 
2507
2522
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
@@ -2603,7 +2618,6 @@ Schema.prototype.virtual = function(name, options) {
2603
2618
  }
2604
2619
 
2605
2620
  const virtuals = this.virtuals;
2606
- const parts = name.split('.');
2607
2621
 
2608
2622
  if (this.pathType(name) === 'real') {
2609
2623
  throw new Error('Virtual path "' + name + '"' +
@@ -2680,12 +2694,30 @@ Schema.prototype.remove = function(path) {
2680
2694
  }
2681
2695
  }
2682
2696
 
2697
+ // Maps under this branch register their values in `mapPaths` as well as in
2698
+ // `paths`. Left behind, they keep answering `pathType()` and casting queries
2699
+ // for a path the schema no longer has.
2700
+ this.mapPaths = this.mapPaths.filter(
2701
+ schemaType => !schemaType.path.startsWith(name + '.')
2702
+ );
2703
+
2683
2704
  delete this.nested[name];
2684
2705
  _deletePath(this, name);
2685
2706
  return;
2686
2707
  }
2687
2708
 
2688
2709
  delete this.paths[name];
2710
+ // A map registers its values under `<path>.$*`, both in `paths` and in
2711
+ // `mapPaths`. Left behind, they keep answering `pathType()` and casting queries
2712
+ // for a path the schema no longer has.
2713
+ for (const subpath of Object.keys(this.paths)) {
2714
+ if (subpath.startsWith(name + '.')) {
2715
+ delete this.paths[subpath];
2716
+ }
2717
+ }
2718
+ this.mapPaths = this.mapPaths.filter(
2719
+ schemaType => !schemaType.path.startsWith(name + '.')
2720
+ );
2689
2721
  _deletePath(this, name);
2690
2722
 
2691
2723
  this._removeEncryptedField(name);
@@ -2706,6 +2738,11 @@ function _deletePath(schema, name) {
2706
2738
 
2707
2739
  for (const piece of pieces) {
2708
2740
  branch = branch[piece];
2741
+ // A synthetic subpath like `<map>.$*` has no branch of its own, and a parent
2742
+ // removed earlier in the same pass leaves none either.
2743
+ if (branch == null) {
2744
+ return;
2745
+ }
2709
2746
  }
2710
2747
 
2711
2748
  delete branch[last];