mongoose 7.8.12 → 7.8.14

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/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');
@@ -29,6 +30,7 @@ const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon'];
29
30
  * @param {Boolean|"throw"} [options.strict] Wheter to enable all strict options
30
31
  * @param {Boolean|"throw"} [options.strictQuery] Enable strict Queries
31
32
  * @param {Boolean} [options.upsert]
33
+ * @param {Boolean} [options.sanitizeFilter] avoid adding implicit query selectors ($in)
32
34
  * @param {Query} [context] passed to setters
33
35
  * @api private
34
36
  */
@@ -109,6 +111,11 @@ module.exports = function cast(schema, obj, options, context) {
109
111
  } else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
110
112
  val = castString(val, path);
111
113
  obj[path] = val;
114
+ } else if (isOperator(path)) {
115
+ // Pass through other top-level operators, like `$jsonSchema`, without casting.
116
+ // MongoDB doesn't allow querying top-level `$` fields, so these can't be paths
117
+ // and `strict` or `strictQuery` shouldn't strip them.
118
+ continue;
112
119
  } else {
113
120
  if (!schema) {
114
121
  // no casting for Mixed types
@@ -139,16 +146,18 @@ module.exports = function cast(schema, obj, options, context) {
139
146
  pathLastHalf !== discriminatorKey) {
140
147
  const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
141
148
  const discriminators = _schematype.schema.discriminators;
142
- if (typeof discriminatorVal === 'string' && discriminators[discriminatorVal] != null) {
143
-
144
- schematype = discriminators[discriminatorVal].path(pathLastHalf);
145
- } else if (discriminatorVal != null &&
149
+ const discriminator = typeof discriminatorVal === 'string' ? getDiscriminatorByKey(discriminators, discriminatorVal) : null;
150
+ const discriminatorFromIn = discriminatorVal != null &&
146
151
  Object.keys(discriminatorVal).length === 1 &&
147
152
  Array.isArray(discriminatorVal.$in) &&
148
153
  discriminatorVal.$in.length === 1 &&
149
- typeof discriminatorVal.$in[0] === 'string' &&
150
- discriminators[discriminatorVal.$in[0]] != null) {
151
- schematype = discriminators[discriminatorVal.$in[0]].path(pathLastHalf);
154
+ typeof discriminatorVal.$in[0] === 'string' ?
155
+ getDiscriminatorByKey(discriminators, discriminatorVal.$in[0]) :
156
+ null;
157
+ if (discriminator != null) {
158
+ schematype = discriminator.path(pathLastHalf);
159
+ } else if (discriminatorFromIn != null) {
160
+ schematype = discriminatorFromIn.path(pathLastHalf);
152
161
  }
153
162
  }
154
163
  }
@@ -372,7 +381,7 @@ module.exports = function cast(schema, obj, options, context) {
372
381
 
373
382
  }
374
383
  }
375
- } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
384
+ } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1 && !options.sanitizeFilter) {
376
385
  const casted = [];
377
386
  const valuesArray = val;
378
387
 
@@ -70,7 +70,14 @@ function QueryCursor(query) {
70
70
  this.listeners('error').length > 0 && this.emit('error', err);
71
71
  return;
72
72
  }
73
- Object.assign(this.options, query._optionsForExec());
73
+ // `_optionsForExec()` can throw, for example if casting the projection fails
74
+ try {
75
+ Object.assign(this.options, query._optionsForExec());
76
+ } catch (err) {
77
+ this._markError(err);
78
+ this.listeners('error').length > 0 && this.emit('error', err);
79
+ return;
80
+ }
74
81
  this._transforms = this._transforms.concat(query._transforms.slice());
75
82
  if (this.options.transform) {
76
83
  this._transforms.push(this.options.transform);
package/lib/document.js CHANGED
@@ -758,7 +758,11 @@ function init(self, obj, doc, opts, prefix) {
758
758
 
759
759
  const value = obj[i];
760
760
  if (!schemaType && utils.isPOJO(value)) {
761
- // assume nested object
761
+ // assume nested object. Skip inherited properties like `Object.prototype.toString`
762
+ // to avoid setting properties on shared objects
763
+ if (!utils.object.hasOwnProperty(doc, i) && i in doc) {
764
+ return;
765
+ }
762
766
  if (!doc[i]) {
763
767
  doc[i] = {};
764
768
  if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
@@ -1726,6 +1730,12 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1726
1730
  } else {
1727
1731
  const isMap = obj instanceof Map;
1728
1732
  let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
1733
+ // Skip inherited properties like `Object.prototype.toString`, document methods,
1734
+ // or document internals like `$__schema` to avoid setting properties on shared
1735
+ // objects. Document properties are getters on the prototype, so check `_doc`.
1736
+ if (!isMap && !utils.object.hasOwnProperty(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1737
+ return;
1738
+ }
1729
1739
  if (utils.isPOJO(value)) {
1730
1740
  obj = value;
1731
1741
  } 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.prototype.hasOwnProperty.call(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('.');
@@ -2,6 +2,9 @@
2
2
 
3
3
  const get = require('../get');
4
4
  const utils = require('../../utils');
5
+
6
+ const simpleCollation = Object.freeze({ locale: 'simple' });
7
+
5
8
  /**
6
9
  * Given a Mongoose index definition (key + options objects) and a MongoDB server
7
10
  * index definition, determine if the two indexes are equal.
@@ -62,14 +65,13 @@ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex)
62
65
  continue;
63
66
  }
64
67
  if (key === 'collation') {
65
- if (options[key] == null || dbIndex[key] == null) {
66
- return options[key] == null && dbIndex[key] == null;
67
- }
68
- const definedKeys = Object.keys(options.collation);
69
- const schemaCollation = options.collation;
70
- const dbCollation = dbIndex.collation;
71
- for (const opt of definedKeys) {
72
- if (get(schemaCollation, opt) !== get(dbCollation, opt)) {
68
+ // No collation is equivalent to { locale: 'simple' }. MongoDB server 9
69
+ // reports { locale: 'simple' } for indexes created with no collation,
70
+ // older versions omit it.
71
+ const schemaCollation = options.collation ?? simpleCollation;
72
+ const dbCollation = dbIndex.collation ?? simpleCollation;
73
+ for (const opt of Object.keys(schemaCollation)) {
74
+ if (schemaCollation[opt] !== dbCollation[opt]) {
73
75
  return false;
74
76
  }
75
77
  }
@@ -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.prototype.hasOwnProperty.call(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');
@@ -712,7 +713,7 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
712
713
  modelNames = [];
713
714
  for (const subdoc of subdocs) {
714
715
  const discriminatorName = utils.getValue(discriminatorKey, subdoc);
715
- const discriminator = schematype.caster.discriminators[discriminatorName];
716
+ const discriminator = getDiscriminatorByKey(schematype.caster.discriminators, discriminatorName);
716
717
  const discriminatorSchema = discriminator && discriminator.schema;
717
718
  if (discriminatorSchema == null) {
718
719
  continue;
@@ -24,7 +24,7 @@ module.exports = function sanitizeFilter(filter) {
24
24
  if (key === '$and' || key === '$or' || key === '$nor') {
25
25
  sanitizeFilter(value);
26
26
  continue;
27
- } else if (key === '$jsonSchema' || key === '$where' || key === '$expr' || key === '$text') {
27
+ } else if (key[0] === '$') {
28
28
  throw new MongooseError(key + ' is not allowed with sanitizeFilter');
29
29
  }
30
30
 
@@ -7,7 +7,24 @@ module.exports = function sanitizeProjection(projection) {
7
7
 
8
8
  const keys = Object.keys(projection);
9
9
  for (let i = 0; i < keys.length; ++i) {
10
- if (typeof projection[keys[i]] === 'string') {
10
+ const value = projection[keys[i]];
11
+ if (typeof value === 'string') {
12
+ projection[keys[i]] = 1;
13
+ continue;
14
+ }
15
+ if (value == null || typeof value !== 'object') {
16
+ continue;
17
+ }
18
+ // Only allow `$meta: 'textScore'`, `$elemMatch`, and numeric `$slice`. Nested sub-projections, arrays, and
19
+ // expressions like `{ name: { $concat: ['$password'] } }` become `1`. Note that
20
+ // `{ $slice: ['$otherArray', 1] }` is an expression that can read another field, and
21
+ // `$meta: 'indexKey'` and `$meta: 'sortKey'` can return values of `select: false` paths.
22
+ const slice = value.$slice;
23
+ const isAllowedProjectionOperator = value.$meta === 'textScore' ||
24
+ value.$elemMatch != null ||
25
+ typeof slice === 'number' ||
26
+ (Array.isArray(slice) && slice.every(v => typeof v === 'number'));
27
+ if (!isAllowedProjectionOperator) {
11
28
  projection[keys[i]] = 1;
12
29
  }
13
30
  }
@@ -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');
@@ -63,7 +64,7 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
63
64
  if (filterBaseSchema != null &&
64
65
  filterBaseSchema.discriminators != null &&
65
66
  filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) {
66
- filterBaseSchema = filterBaseSchema.discriminators[filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]] || filterBaseSchema;
67
+ filterBaseSchema = getDiscriminatorByKey(filterBaseSchema.discriminators, filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey]) || filterBaseSchema;
67
68
  }
68
69
 
69
70
  for (const key of keys) {
package/lib/model.js CHANGED
@@ -42,6 +42,7 @@ const firstKey = require('./helpers/firstKey');
42
42
  const each = require('./helpers/each');
43
43
  const get = require('./helpers/get');
44
44
  const getConstructorName = require('./helpers/getConstructorName');
45
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
45
46
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
46
47
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
47
48
  const immediate = require('./helpers/immediate');
@@ -2878,7 +2879,7 @@ Model.create = async function create(doc, options) {
2878
2879
  try {
2879
2880
  const doc = args[i];
2880
2881
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2881
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2882
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2882
2883
  this;
2883
2884
  if (Model == null) {
2884
2885
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -2905,7 +2906,7 @@ Model.create = async function create(doc, options) {
2905
2906
  const promiseType = !immediateError ? Promise.allSettled.bind(Promise) : Promise.all.bind(Promise);
2906
2907
  let p = promiseType(args.map(async doc => {
2907
2908
  const Model = this.discriminators && doc[discriminatorKey] != null ?
2908
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2909
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
2909
2910
  this;
2910
2911
  if (Model == null) {
2911
2912
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -4757,7 +4758,7 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
4757
4758
  }
4758
4759
 
4759
4760
  // If discriminator key is set, use the discriminator instead (gh-7586)
4760
- const Discriminator = model.discriminators[doc[discriminatorKey]] ||
4761
+ const Discriminator = getDiscriminatorByKey(model.discriminators, doc[discriminatorKey]) ||
4761
4762
  getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
4762
4763
  if (Discriminator != null) {
4763
4764
  return new Discriminator(doc, fields, skipId);
package/lib/query.js CHANGED
@@ -20,6 +20,7 @@ const castNumber = require('./cast/number');
20
20
  const castUpdate = require('./helpers/query/castUpdate');
21
21
  const clone = require('./helpers/clone');
22
22
  const completeMany = require('./helpers/query/completeMany');
23
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
23
24
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
24
25
  const hasDollarKeys = require('./helpers/query/hasDollarKeys');
25
26
  const helpers = require('./queryhelpers');
@@ -37,6 +38,7 @@ const sanitizeFilter = require('./helpers/query/sanitizeFilter');
37
38
  const sanitizeProjection = require('./helpers/query/sanitizeProjection');
38
39
  const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
39
40
  const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
41
+ const specialProperties = require('./helpers/specialProperties');
40
42
  const updateValidators = require('./helpers/updateValidators');
41
43
  const util = require('util');
42
44
  const utils = require('./utils');
@@ -371,6 +373,14 @@ Query.prototype.clone = function() {
371
373
  * @api public
372
374
  */
373
375
 
376
+ Query.prototype.where = function where(path) {
377
+ if (typeof path === 'string' && specialProperties.has(path)) {
378
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
379
+ }
380
+
381
+ return Query.base.where.apply(this, arguments);
382
+ };
383
+
374
384
  /**
375
385
  * Specifies a `$slice` projection for an array.
376
386
  *
@@ -747,7 +757,13 @@ Query.prototype.mod = function() {
747
757
  path = arguments[0];
748
758
  }
749
759
 
750
- const conds = this._conditions[path] || (this._conditions[path] = {});
760
+ if (path != null && specialProperties.has(String(path))) {
761
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
762
+ }
763
+
764
+ // Avoid reusing inherited properties like `toString`
765
+ const conds = (utils.object.hasOwnProperty(this._conditions, path) && this._conditions[path]) ||
766
+ (this._conditions[path] = {});
751
767
  conds.$mod = val;
752
768
  return this;
753
769
  };
@@ -1084,6 +1100,11 @@ Query.prototype.select = function select() {
1084
1100
  }
1085
1101
  arg = parseProjection(arg, true); // we want to keep the minus and pluses, so add boolean arg.
1086
1102
  if (utils.isObject(arg)) {
1103
+ // `fields['__proto__'] = value` would re-point the projection's prototype
1104
+ if (Object.prototype.hasOwnProperty.call(arg, '__proto__')) {
1105
+ arg = { ...arg };
1106
+ delete arg['__proto__'];
1107
+ }
1087
1108
  if (this.selectedInclusively()) {
1088
1109
  Object.entries(arg).forEach(([key, value]) => {
1089
1110
  if (value) {
@@ -2220,14 +2241,10 @@ Query.prototype.mongooseOptions = function(v) {
2220
2241
  */
2221
2242
 
2222
2243
  Query.prototype._castConditions = function() {
2223
- let sanitizeFilterOpt = undefined;
2224
- if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeFilter')) {
2225
- sanitizeFilterOpt = this.model.db.options.sanitizeFilter;
2226
- } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeFilter')) {
2227
- sanitizeFilterOpt = this.model.base.options.sanitizeFilter;
2228
- } else {
2229
- sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter;
2230
- }
2244
+ const sanitizeFilterOpt = this.model?.db.config?.sanitizeFilter ??
2245
+ this.model?.db.options?.sanitizeFilter ??
2246
+ this.model?.base.options.sanitizeFilter ??
2247
+ this._mongooseOptions.sanitizeFilter;
2231
2248
 
2232
2249
  if (sanitizeFilterOpt) {
2233
2250
  sanitizeFilter(this._conditions);
@@ -4711,7 +4728,7 @@ Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
4711
4728
  schema.discriminators != null) {
4712
4729
  const discriminatorValue = filter[schema.options.discriminatorKey];
4713
4730
  const byValue = getDiscriminatorByValue(this.model.discriminators, discriminatorValue);
4714
- schema = schema.discriminators[discriminatorValue] ||
4731
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
4715
4732
  (byValue && byValue.schema) ||
4716
4733
  schema;
4717
4734
  }
@@ -4914,6 +4931,10 @@ Query.prototype.cast = function(model, obj) {
4914
4931
  opts.strictQuery = this.options.strictQuery;
4915
4932
  }
4916
4933
  }
4934
+ opts.sanitizeFilter = model.db.config?.sanitizeFilter ??
4935
+ model.db.options?.sanitizeFilter ??
4936
+ model.base.options.sanitizeFilter ??
4937
+ this._mongooseOptions.sanitizeFilter;
4917
4938
 
4918
4939
  try {
4919
4940
  return cast(model.schema, obj, opts, this);
@@ -4961,11 +4982,7 @@ Query.prototype._castFields = function _castFields(fields) {
4961
4982
 
4962
4983
  if (selected) {
4963
4984
  // they passed $elemMatch, cast em
4964
- try {
4965
- out = this.cast(this.model, selected);
4966
- } catch (err) {
4967
- return err;
4968
- }
4985
+ out = this.cast(this.model, selected);
4969
4986
 
4970
4987
  // apply the casted field args
4971
4988
  for (let i = 0; i < elemMatchKeys.length; ++i) {
@@ -4987,6 +5004,20 @@ Query.prototype._applyPaths = function applyPaths() {
4987
5004
  return;
4988
5005
  }
4989
5006
  this._fields = this._fields || {};
5007
+
5008
+ let shouldSanitizeProjection = undefined;
5009
+ if (utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5010
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5011
+ } else if (utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5012
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5013
+ } else {
5014
+ shouldSanitizeProjection = this._mongooseOptions.sanitizeProjection;
5015
+ }
5016
+ // Strip expressions at exec time, because projections may be set before `sanitizeProjection`
5017
+ if (shouldSanitizeProjection) {
5018
+ sanitizeProjection(this._fields);
5019
+ }
5020
+
4990
5021
  helpers.applyPaths(this._fields, this.model.schema);
4991
5022
 
4992
5023
  let _selectPopulatedPaths = true;
@@ -4,12 +4,15 @@
4
4
  * Module dependencies
5
5
  */
6
6
 
7
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
7
8
  const checkEmbeddedDiscriminatorKeyProjection =
8
9
  require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection');
9
10
  const get = require('./helpers/get');
10
11
  const getDiscriminatorByValue =
11
12
  require('./helpers/discriminator/getDiscriminatorByValue');
12
13
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
14
+ const isExclusive = require('./helpers/projection/isExclusive');
15
+ const isPOJO = require('./helpers/isPOJO');
13
16
  const clone = require('./helpers/clone');
14
17
  const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
15
18
 
@@ -105,7 +108,7 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
105
108
 
106
109
  const value = doc[key];
107
110
  if (key && value && model.discriminators) {
108
- const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
111
+ const discriminator = getDiscriminatorByKey(model.discriminators, value) || getDiscriminatorByValue(model.discriminators, value);
109
112
  if (discriminator) {
110
113
  const _fields = clone(userProvidedFields);
111
114
  exports.applyPaths(_fields, discriminator.schema);
@@ -171,6 +174,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
171
174
  }
172
175
 
173
176
  keys = Object.keys(fields);
177
+ let hasElemMatch = false;
174
178
  for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) {
175
179
  if (keys[keyIndex][0] === '+') {
176
180
  continue;
@@ -180,15 +184,32 @@ exports.applyPaths = function applyPaths(fields, schema) {
180
184
  if (!isDefiningProjection(field)) {
181
185
  continue;
182
186
  }
187
+ // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
188
+ if (field?.$elemMatch != null) {
189
+ hasElemMatch = true;
190
+ continue;
191
+ }
183
192
  if (keys[keyIndex] === '_id' && keys.length > 1) {
184
193
  continue;
185
194
  }
186
195
  if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) {
187
196
  continue;
188
197
  }
198
+ // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
199
+ // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
200
+ if (isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
201
+ exclude = isExclusive(field) ?? undefined;
202
+ if (exclude === undefined) {
203
+ continue;
204
+ }
205
+ break;
206
+ }
189
207
  exclude = !field;
190
208
  break;
191
209
  }
210
+ if (exclude === undefined && hasElemMatch) {
211
+ exclude = false;
212
+ }
192
213
 
193
214
  // Potentially add back minus paths based on schema-level path config
194
215
  // and whether the projection is inclusive
@@ -19,6 +19,7 @@ const util = require('util');
19
19
  const utils = require('../utils');
20
20
  const castToNumber = require('./operators/helpers').castToNumber;
21
21
  const geospatial = require('./operators/geospatial');
22
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
22
23
  const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
23
24
 
24
25
  let MongooseArray;
@@ -497,9 +498,11 @@ SchemaArray.prototype._castForQuery = function(val, context) {
497
498
  Constructor.schema &&
498
499
  Constructor.schema.options &&
499
500
  Constructor.schema.options.discriminatorKey) {
500
- if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
501
- Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
502
- Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
501
+ const discriminator = typeof val[Constructor.schema.options.discriminatorKey] === 'string' ?
502
+ getDiscriminatorByKey(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]) :
503
+ null;
504
+ if (discriminator) {
505
+ Constructor = discriminator;
503
506
  } else {
504
507
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]);
505
508
  if (constructorByValue) {
@@ -618,10 +621,11 @@ function cast$elemMatch(val, context) {
618
621
  this.casterConstructor &&
619
622
  this.casterConstructor.schema &&
620
623
  this.casterConstructor.schema.discriminators || {};
621
- if (discriminatorKey != null &&
622
- val[discriminatorKey] != null &&
623
- discriminators[val[discriminatorKey]] != null) {
624
- return cast(discriminators[val[discriminatorKey]], val, null, this && this.$$context);
624
+ const discriminator = discriminatorKey != null && val[discriminatorKey] != null ?
625
+ getDiscriminatorByKey(discriminators, val[discriminatorKey]) :
626
+ null;
627
+ if (discriminator != null) {
628
+ return cast(discriminator, val, null, this && this.$$context);
625
629
  }
626
630
  const schema = this.casterConstructor.schema ?? context.schema;
627
631
  return cast(schema, val, null, this && this.$$context);
package/lib/schema.js CHANGED
@@ -2244,6 +2244,12 @@ Schema.prototype.virtual = function(name, options) {
2244
2244
  if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2245
2245
  return this.virtual(name.path, name.options);
2246
2246
  }
2247
+ const parts = name.split('.');
2248
+ for (const part of parts) {
2249
+ if (utils.specialProperties.has(part)) {
2250
+ throw new MongooseError('Cannot set special property `' + part + '` on a schema');
2251
+ }
2252
+ }
2247
2253
  options = new VirtualOptions(options);
2248
2254
 
2249
2255
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
@@ -2330,7 +2336,6 @@ Schema.prototype.virtual = function(name, options) {
2330
2336
  }
2331
2337
 
2332
2338
  const virtuals = this.virtuals;
2333
- const parts = name.split('.');
2334
2339
 
2335
2340
  if (this.pathType(name) === 'real') {
2336
2341
  throw new Error('Virtual path "' + name + '"' +
@@ -3,6 +3,7 @@
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
5
  const castObjectId = require('../../../cast/objectid');
6
+ const getDiscriminatorByKey = require('../../../helpers/discriminator/getDiscriminatorByKey');
6
7
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
7
8
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
8
9
  const utils = require('../../../utils');
@@ -75,9 +76,11 @@ const methods = {
75
76
  Constructor.schema &&
76
77
  Constructor.schema.options &&
77
78
  Constructor.schema.options.discriminatorKey) {
78
- if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
79
- Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
80
- Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
79
+ const discriminator = typeof value[Constructor.schema.options.discriminatorKey] === 'string' ?
80
+ getDiscriminatorByKey(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]) :
81
+ null;
82
+ if (discriminator) {
83
+ Constructor = discriminator;
81
84
  } else {
82
85
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
83
86
  if (constructorByValue) {
@@ -268,9 +271,11 @@ const methods = {
268
271
  Constructor.schema &&
269
272
  Constructor.schema.options &&
270
273
  Constructor.schema.options.discriminatorKey) {
271
- if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
272
- Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
273
- Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
274
+ const discriminator = typeof obj[Constructor.schema.options.discriminatorKey] === 'string' ?
275
+ getDiscriminatorByKey(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]) :
276
+ null;
277
+ if (discriminator) {
278
+ Constructor = discriminator;
274
279
  } else {
275
280
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
276
281
  if (constructorByValue) {
package/lib/utils.js CHANGED
@@ -882,6 +882,12 @@ exports.mergeClone = function(to, fromObj) {
882
882
  if (specialProperties.has(key)) {
883
883
  continue;
884
884
  }
885
+ // Skip inherited properties like `Object.prototype.toString` to avoid setting
886
+ // properties on shared objects. Document properties are getters on the
887
+ // prototype, so check `_doc`.
888
+ if (!exports.object.hasOwnProperty(to.$__ == null ? to : to._doc, key) && key in to) {
889
+ continue;
890
+ }
885
891
  if (typeof to[key] === 'undefined') {
886
892
  to[key] = clone(fromObj[key], {
887
893
  transform: false,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "7.8.12",
4
+ "version": "7.8.14",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -23,7 +23,7 @@
23
23
  "kareem": "2.5.1",
24
24
  "mongodb": "5.9.2",
25
25
  "mpath": "0.9.0",
26
- "mquery": "5.0.0",
26
+ "mquery": "5.0.1",
27
27
  "ms": "2.1.3",
28
28
  "sift": "16.0.1"
29
29
  },