mongoose 6.13.11 → 6.13.13

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
  */
@@ -103,6 +105,11 @@ module.exports = function cast(schema, obj, options, context) {
103
105
  } else if (path === '$comment' && !schema.paths.hasOwnProperty('$comment')) {
104
106
  val = castString(val, path);
105
107
  obj[path] = val;
108
+ } else if (isOperator(path)) {
109
+ // Pass through other top-level operators, like `$jsonSchema`, without casting.
110
+ // MongoDB doesn't allow querying top-level `$` fields, so these can't be paths
111
+ // and `strict` or `strictQuery` shouldn't strip them.
112
+ continue;
106
113
  } else {
107
114
  if (!schema) {
108
115
  // no casting for Mixed types
@@ -132,9 +139,11 @@ module.exports = function cast(schema, obj, options, context) {
132
139
  discriminatorKey != null &&
133
140
  pathLastHalf !== discriminatorKey) {
134
141
  const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey);
135
- if (discriminatorVal != null) {
136
- schematype = _schematype.schema.discriminators[discriminatorVal].
137
- path(pathLastHalf);
142
+ const discriminator = discriminatorVal != null ?
143
+ getDiscriminatorByKey(_schematype.schema.discriminators, discriminatorVal) :
144
+ null;
145
+ if (discriminator != null) {
146
+ schematype = discriminator.path(pathLastHalf);
138
147
  }
139
148
  }
140
149
  }
@@ -340,7 +349,7 @@ module.exports = function cast(schema, obj, options, context) {
340
349
  }
341
350
  }
342
351
  }
343
- } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
352
+ } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1 && !options.sanitizeFilter) {
344
353
  const casted = [];
345
354
  const valuesArray = val;
346
355
 
@@ -66,7 +66,14 @@ function QueryCursor(query, options) {
66
66
  // Max out the number of documents we'll populate in parallel at 5000.
67
67
  this.options._populateBatchSize = Math.min(this.options.batchSize, 5000);
68
68
  }
69
- Object.assign(this.options, query._optionsForExec());
69
+ // `_optionsForExec()` can throw, for example if casting the projection fails
70
+ try {
71
+ Object.assign(this.options, query._optionsForExec());
72
+ } catch (err) {
73
+ _this._markError(err);
74
+ _this.listeners('error').length > 0 && _this.emit('error', err);
75
+ return;
76
+ }
70
77
  model.collection.find(query._conditions, this.options, (err, cursor) => {
71
78
  if (err != null) {
72
79
  _this._markError(err);
package/lib/document.js CHANGED
@@ -754,7 +754,11 @@ function init(self, obj, doc, opts, prefix) {
754
754
 
755
755
  const value = obj[i];
756
756
  if (!schemaType && utils.isPOJO(value)) {
757
- // assume nested object
757
+ // assume nested object. Skip inherited properties like `Object.prototype.toString`
758
+ // to avoid setting properties on shared objects
759
+ if (!utils.object.hasOwnProperty(doc, i) && i in doc) {
760
+ return;
761
+ }
758
762
  if (!doc[i]) {
759
763
  doc[i] = {};
760
764
  if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
@@ -1722,6 +1726,12 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1722
1726
  obj[parts[i]] = val;
1723
1727
  }
1724
1728
  } else {
1729
+ // Skip inherited properties like `Object.prototype.toString`, document methods,
1730
+ // or document internals like `$__schema` to avoid setting properties on shared
1731
+ // objects. Document properties are getters on the prototype, so check `_doc`.
1732
+ if (!utils.object.hasOwnProperty(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1733
+ return;
1734
+ }
1725
1735
  if (utils.isPOJO(obj[parts[i]])) {
1726
1736
  obj = obj[parts[i]];
1727
1737
  } else if (obj[parts[i]] && obj[parts[i]] 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
  /**
@@ -12,8 +13,9 @@ module.exports = function getConstructor(Constructor, value) {
12
13
  if (value != null &&
13
14
  Constructor.discriminators &&
14
15
  value[discriminatorKey] != null) {
15
- if (Constructor.discriminators[value[discriminatorKey]]) {
16
- Constructor = Constructor.discriminators[value[discriminatorKey]];
16
+ const discriminator = getDiscriminatorByKey(Constructor.discriminators, value[discriminatorKey]);
17
+ if (discriminator) {
18
+ Constructor = discriminator;
17
19
  } else {
18
20
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[discriminatorKey]);
19
21
  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
 
@@ -37,7 +38,7 @@ module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) {
37
38
  const discriminators = schemaType.schema.discriminators;
38
39
  const discriminatorKey = doc.get(subpath + '.' +
39
40
  get(schemaType, 'schema.options.discriminatorKey'));
40
- if (discriminatorKey == null || discriminators[discriminatorKey] == null) {
41
+ if (discriminatorKey == null || getDiscriminatorByKey(discriminators, discriminatorKey) == null) {
41
42
  continue;
42
43
  }
43
44
  const rest = parts.slice(i + 1).join('.');
@@ -9,7 +9,9 @@ function isBsonType(obj, typename) {
9
9
  return (
10
10
  typeof obj === 'object' &&
11
11
  obj !== null &&
12
- obj._bsontype === typename
12
+ obj._bsontype === typename &&
13
+ // bson defines `_bsontype` on the prototype, so an own `_bsontype` means a plain object pretending to be a bson value
14
+ !Object.prototype.hasOwnProperty.call(obj, '_bsontype')
13
15
  );
14
16
  }
15
17
 
@@ -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
  }
@@ -3,6 +3,7 @@
3
3
  const MongooseError = require('../../error/index');
4
4
  const SkipPopulateValue = require('./SkipPopulateValue');
5
5
  const get = require('../get');
6
+ const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
6
7
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
7
8
  const getConstructorName = require('../getConstructorName');
8
9
  const getSchemaTypes = require('./getSchemaTypes');
@@ -710,7 +711,7 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
710
711
  modelNames = [];
711
712
  for (const subdoc of subdocs) {
712
713
  const discriminatorName = utils.getValue(discriminatorKey, subdoc);
713
- const discriminator = schematype.caster.discriminators[discriminatorName];
714
+ const discriminator = getDiscriminatorByKey(schematype.caster.discriminators, discriminatorName);
714
715
  const discriminatorSchema = discriminator && discriminator.schema;
715
716
  if (discriminatorSchema == null) {
716
717
  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
  }
@@ -26,6 +26,11 @@ module.exports = function wrapThunk(fn) {
26
26
  }
27
27
  this._executionStack = new Error().stack;
28
28
 
29
- fn.call(this, cb);
29
+ // Thunks can throw synchronously, for example if `_optionsForExec()` fails to cast the projection
30
+ try {
31
+ fn.call(this, cb);
32
+ } catch (err) {
33
+ cb(err);
34
+ }
30
35
  };
31
36
  };
@@ -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
@@ -43,6 +43,7 @@ const firstKey = require('./helpers/firstKey');
43
43
  const each = require('./helpers/each');
44
44
  const get = require('./helpers/get');
45
45
  const getConstructorName = require('./helpers/getConstructorName');
46
+ const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
46
47
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
47
48
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
48
49
  const immediate = require('./helpers/immediate');
@@ -3191,7 +3192,7 @@ Model.create = function create(doc, options, callback) {
3191
3192
  args.forEach(doc => {
3192
3193
  toExecute.push(callback => {
3193
3194
  const Model = this.discriminators && doc[discriminatorKey] != null ?
3194
- this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
3195
+ getDiscriminatorByKey(this.discriminators, doc[discriminatorKey]) || getDiscriminatorByValue(this.discriminators, doc[discriminatorKey]) :
3195
3196
  this;
3196
3197
  if (Model == null) {
3197
3198
  throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` +
@@ -5241,7 +5242,7 @@ Model.compile = function compile(name, schema, collectionName, connection, base)
5241
5242
  }
5242
5243
 
5243
5244
  // If discriminator key is set, use the discriminator instead (gh-7586)
5244
- const Discriminator = model.discriminators[doc[discriminatorKey]] ||
5245
+ const Discriminator = getDiscriminatorByKey(model.discriminators, doc[discriminatorKey]) ||
5245
5246
  getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
5246
5247
  if (Discriminator != null) {
5247
5248
  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 completeMany = require('./helpers/query/completeMany');
22
22
  const promiseOrCallback = require('./helpers/promiseOrCallback');
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');
@@ -35,6 +36,7 @@ const sanitizeFilter = require('./helpers/query/sanitizeFilter');
35
36
  const sanitizeProjection = require('./helpers/query/sanitizeProjection');
36
37
  const selectPopulatedFields = require('./helpers/query/selectPopulatedFields');
37
38
  const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert');
39
+ const specialProperties = require('./helpers/specialProperties');
38
40
  const updateValidators = require('./helpers/updateValidators');
39
41
  const util = require('util');
40
42
  const utils = require('./utils');
@@ -365,6 +367,14 @@ Query.prototype.clone = function clone() {
365
367
  * @api public
366
368
  */
367
369
 
370
+ Query.prototype.where = function where(path) {
371
+ if (typeof path === 'string' && specialProperties.has(path)) {
372
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
373
+ }
374
+
375
+ return Query.base.where.apply(this, arguments);
376
+ };
377
+
368
378
  /**
369
379
  * Specifies a `$slice` projection for an array.
370
380
  *
@@ -741,7 +751,13 @@ Query.prototype.mod = function() {
741
751
  path = arguments[0];
742
752
  }
743
753
 
744
- const conds = this._conditions[path] || (this._conditions[path] = {});
754
+ if (path != null && specialProperties.has(String(path))) {
755
+ throw new MongooseError(`Cannot use \`${path}\` as a query path`);
756
+ }
757
+
758
+ // Avoid reusing inherited properties like `toString`
759
+ const conds = (utils.object.hasOwnProperty(this._conditions, path) && this._conditions[path]) ||
760
+ (this._conditions[path] = {});
745
761
  conds.$mod = val;
746
762
  return this;
747
763
  };
@@ -1119,6 +1135,11 @@ Query.prototype.select = function select() {
1119
1135
  arg = parseProjection(arg);
1120
1136
 
1121
1137
  if (utils.isObject(arg)) {
1138
+ // `fields['__proto__'] = value` would re-point the projection's prototype
1139
+ if (Object.prototype.hasOwnProperty.call(arg, '__proto__')) {
1140
+ arg = { ...arg };
1141
+ delete arg['__proto__'];
1142
+ }
1122
1143
  if (this.selectedInclusively()) {
1123
1144
  Object.entries(arg).forEach(([key, value]) => {
1124
1145
  if (value) {
@@ -2213,19 +2234,20 @@ Query.prototype.mongooseOptions = function(v) {
2213
2234
 
2214
2235
  Query.prototype._castConditions = function() {
2215
2236
  let sanitizeFilterOpt = undefined;
2216
- if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeFilter')) {
2237
+ if (this.model != null && this.model.db.config != null && this.model.db.config.sanitizeFilter != null) {
2238
+ sanitizeFilterOpt = this.model.db.config.sanitizeFilter;
2239
+ } else if (this.model != null && this.model.db.options != null && this.model.db.options.sanitizeFilter != null) {
2217
2240
  sanitizeFilterOpt = this.model.db.options.sanitizeFilter;
2218
- } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeFilter')) {
2241
+ } else if (this.model != null && this.model.base.options != null && this.model.base.options.sanitizeFilter != null) {
2219
2242
  sanitizeFilterOpt = this.model.base.options.sanitizeFilter;
2220
2243
  } else {
2221
2244
  sanitizeFilterOpt = this._mongooseOptions.sanitizeFilter;
2222
2245
  }
2223
2246
 
2224
- if (sanitizeFilterOpt) {
2225
- sanitizeFilter(this._conditions);
2226
- }
2227
-
2228
2247
  try {
2248
+ if (sanitizeFilterOpt) {
2249
+ sanitizeFilter(this._conditions);
2250
+ }
2229
2251
  this.cast(this.model);
2230
2252
  this._unsetCastError();
2231
2253
  } catch (err) {
@@ -3698,15 +3720,9 @@ Query.prototype._findOneAndDelete = wrapThunk(function(callback) {
3698
3720
 
3699
3721
  const filter = this._conditions;
3700
3722
  const options = this._optionsForExec();
3701
- let fields = null;
3702
3723
 
3703
3724
  if (this._fields != null) {
3704
3725
  options.projection = this._castFields(utils.clone(this._fields));
3705
- fields = options.projection;
3706
- if (fields instanceof Error) {
3707
- callback(fields);
3708
- return null;
3709
- }
3710
3726
  }
3711
3727
 
3712
3728
  this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => {
@@ -5132,7 +5148,7 @@ Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
5132
5148
  schema.discriminators != null) {
5133
5149
  const discriminatorValue = filter[schema.options.discriminatorKey];
5134
5150
  const byValue = getDiscriminatorByValue(this.model.discriminators, discriminatorValue);
5135
- schema = schema.discriminators[discriminatorValue] ||
5151
+ schema = getDiscriminatorByKey(schema.discriminators, discriminatorValue) ||
5136
5152
  (byValue && byValue.schema) ||
5137
5153
  schema;
5138
5154
  }
@@ -5153,7 +5169,8 @@ Query.prototype._castUpdate = function _castUpdate(obj, overwrite) {
5153
5169
 
5154
5170
  function castQuery(query) {
5155
5171
  try {
5156
- return query.cast(query.model);
5172
+ query._castConditions();
5173
+ return query.error() || query._conditions;
5157
5174
  } catch (err) {
5158
5175
  return err;
5159
5176
  }
@@ -5350,6 +5367,15 @@ Query.prototype.cast = function(model, obj) {
5350
5367
  opts.strictQuery = this.options.strictQuery;
5351
5368
  }
5352
5369
  }
5370
+ if (model.db.config != null && model.db.config.sanitizeFilter != null) {
5371
+ opts.sanitizeFilter = model.db.config.sanitizeFilter;
5372
+ } else if (model.db.options != null && model.db.options.sanitizeFilter != null) {
5373
+ opts.sanitizeFilter = model.db.options.sanitizeFilter;
5374
+ } else if (model.base.options != null && model.base.options.sanitizeFilter != null) {
5375
+ opts.sanitizeFilter = model.base.options.sanitizeFilter;
5376
+ } else {
5377
+ opts.sanitizeFilter = this._mongooseOptions.sanitizeFilter;
5378
+ }
5353
5379
 
5354
5380
  try {
5355
5381
  return cast(model.schema, obj, opts, this);
@@ -5399,11 +5425,7 @@ Query.prototype._castFields = function _castFields(fields) {
5399
5425
 
5400
5426
  if (selected) {
5401
5427
  // they passed $elemMatch, cast em
5402
- try {
5403
- out = this.cast(this.model, selected);
5404
- } catch (err) {
5405
- return err;
5406
- }
5428
+ out = this.cast(this.model, selected);
5407
5429
 
5408
5430
  // apply the casted field args
5409
5431
  i = elemMatchKeys.length;
@@ -5426,6 +5448,20 @@ Query.prototype._applyPaths = function applyPaths() {
5426
5448
  return;
5427
5449
  }
5428
5450
  this._fields = this._fields || {};
5451
+
5452
+ let shouldSanitizeProjection = undefined;
5453
+ if (utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5454
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5455
+ } else if (utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5456
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5457
+ } else {
5458
+ shouldSanitizeProjection = this._mongooseOptions.sanitizeProjection;
5459
+ }
5460
+ // Strip expressions at exec time, because projections may be set before `sanitizeProjection`
5461
+ if (shouldSanitizeProjection) {
5462
+ sanitizeProjection(this._fields);
5463
+ }
5464
+
5429
5465
  helpers.applyPaths(this._fields, this.model.schema);
5430
5466
 
5431
5467
  let _selectPopulatedPaths = true;
@@ -5487,8 +5523,10 @@ Query.prototype.cursor = function cursor(opts) {
5487
5523
  this.setOptions(opts);
5488
5524
  }
5489
5525
 
5490
- const options = this._optionsForExec();
5526
+ let options;
5491
5527
  try {
5528
+ // `_optionsForExec()` throws if casting the projection fails
5529
+ options = this._optionsForExec();
5492
5530
  this._castConditions();
5493
5531
  } catch (err) {
5494
5532
  // `_castConditions()` reports cast errors on the query, but `sanitizeFilter`
@@ -4,13 +4,16 @@
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');
13
15
  const clone = require('./helpers/clone');
16
+ const utils = require('./utils');
14
17
 
15
18
  /**
16
19
  * Prepare a set of path options for query population.
@@ -104,7 +107,7 @@ exports.createModel = function createModel(model, doc, fields, userProvidedField
104
107
 
105
108
  const value = doc[key];
106
109
  if (key && value && model.discriminators) {
107
- const discriminator = model.discriminators[value] || getDiscriminatorByValue(model.discriminators, value);
110
+ const discriminator = getDiscriminatorByKey(model.discriminators, value) || getDiscriminatorByValue(model.discriminators, value);
108
111
  if (discriminator) {
109
112
  const _fields = clone(userProvidedFields);
110
113
  exports.applyPaths(_fields, discriminator.schema);
@@ -153,6 +156,7 @@ exports.applyPaths = function applyPaths(fields, schema) {
153
156
  if (fields) {
154
157
  keys = Object.keys(fields);
155
158
  keyIndex = keys.length;
159
+ let hasElemMatch = false;
156
160
 
157
161
  while (keyIndex--) {
158
162
  if (keys[keyIndex][0] === '+') {
@@ -163,14 +167,32 @@ exports.applyPaths = function applyPaths(fields, schema) {
163
167
  if (!isDefiningProjection(field)) {
164
168
  continue;
165
169
  }
170
+ // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
171
+ if (field != null && field.$elemMatch != null) {
172
+ hasElemMatch = true;
173
+ continue;
174
+ }
166
175
  // `_id: 1, name: 0` is a mixed inclusive/exclusive projection in
167
176
  // MongoDB 4.0 and earlier, but not in later versions.
168
177
  if (keys[keyIndex] === '_id' && keys.length > 1) {
169
178
  continue;
170
179
  }
180
+ // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
181
+ // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
182
+ if (utils.isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
183
+ const nestedExclude = isExclusive(field);
184
+ if (nestedExclude == null) {
185
+ continue;
186
+ }
187
+ exclude = nestedExclude;
188
+ break;
189
+ }
171
190
  exclude = !field;
172
191
  break;
173
192
  }
193
+ if (exclude === undefined && hasElemMatch) {
194
+ exclude = false;
195
+ }
174
196
  }
175
197
 
176
198
  // if selecting, apply default schematype select:true fields
@@ -18,6 +18,7 @@ const util = require('util');
18
18
  const utils = require('../utils');
19
19
  const castToNumber = require('./operators/helpers').castToNumber;
20
20
  const geospatial = require('./operators/geospatial');
21
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
21
22
  const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
22
23
 
23
24
  let MongooseArray;
@@ -506,9 +507,11 @@ SchemaArray.prototype.castForQuery = function($conditional, value) {
506
507
  Constructor.schema &&
507
508
  Constructor.schema.options &&
508
509
  Constructor.schema.options.discriminatorKey) {
509
- if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
510
- Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
511
- Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
510
+ const discriminator = typeof val[Constructor.schema.options.discriminatorKey] === 'string' ?
511
+ getDiscriminatorByKey(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]) :
512
+ null;
513
+ if (discriminator) {
514
+ Constructor = discriminator;
512
515
  } else {
513
516
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, val[Constructor.schema.options.discriminatorKey]);
514
517
  if (constructorByValue) {
@@ -595,10 +598,11 @@ function cast$elemMatch(val) {
595
598
  this.casterConstructor &&
596
599
  this.casterConstructor.schema &&
597
600
  this.casterConstructor.schema.discriminators || {};
598
- if (discriminatorKey != null &&
599
- val[discriminatorKey] != null &&
600
- discriminators[val[discriminatorKey]] != null) {
601
- return cast(discriminators[val[discriminatorKey]], val, null, this && this.$$context);
601
+ const discriminator = discriminatorKey != null && val[discriminatorKey] != null ?
602
+ getDiscriminatorByKey(discriminators, val[discriminatorKey]) :
603
+ null;
604
+ if (discriminator != null) {
605
+ return cast(discriminator, val, null, this && this.$$context);
602
606
  }
603
607
 
604
608
  return cast(this.casterConstructor.schema, val, null, this && this.$$context);
package/lib/schema.js CHANGED
@@ -2142,6 +2142,12 @@ Schema.prototype.virtual = function(name, options) {
2142
2142
  if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2143
2143
  return this.virtual(name.path, name.options);
2144
2144
  }
2145
+ const parts = name.split('.');
2146
+ for (const part of parts) {
2147
+ if (utils.specialProperties.has(part)) {
2148
+ throw new MongooseError('Cannot set special property `' + part + '` on a schema');
2149
+ }
2150
+ }
2145
2151
  options = new VirtualOptions(options);
2146
2152
 
2147
2153
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
@@ -2224,7 +2230,6 @@ Schema.prototype.virtual = function(name, options) {
2224
2230
  }
2225
2231
 
2226
2232
  const virtuals = this.virtuals;
2227
- const parts = name.split('.');
2228
2233
 
2229
2234
  if (this.pathType(name) === 'real') {
2230
2235
  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
@@ -905,6 +905,12 @@ exports.mergeClone = function(to, fromObj) {
905
905
  if (specialProperties.has(key)) {
906
906
  continue;
907
907
  }
908
+ // Skip inherited properties like `Object.prototype.toString` to avoid setting
909
+ // properties on shared objects. Document properties are getters on the
910
+ // prototype, so check `_doc`.
911
+ if (!exports.object.hasOwnProperty(to.$__ == null ? to : to._doc, key) && key in to) {
912
+ continue;
913
+ }
908
914
  if (typeof to[key] === 'undefined') {
909
915
  to[key] = exports.clone(fromObj[key], {
910
916
  transform: false,