mongoose 9.12.2 → 9.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/lib/aggregate.js +4 -0
  2. package/lib/cast.js +4 -2
  3. package/lib/connection.js +11 -8
  4. package/lib/defaults/schemaDefaultsCache.js +62 -0
  5. package/lib/document.js +69 -53
  6. package/lib/filters/operators.js +8 -0
  7. package/lib/helpers/clone.js +9 -8
  8. package/lib/helpers/document/applyDefaults.js +1 -1
  9. package/lib/helpers/document/compile.js +2 -1
  10. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  11. package/lib/helpers/getInheritedProperty.js +28 -0
  12. package/lib/helpers/getOwnProperty.js +19 -0
  13. package/lib/helpers/isMongooseDocument.js +24 -0
  14. package/lib/helpers/isMongooseObject.js +5 -3
  15. package/lib/helpers/model/discriminator.js +9 -3
  16. package/lib/helpers/parallelLimit.js +31 -11
  17. package/lib/helpers/populate/assignVals.js +10 -8
  18. package/lib/helpers/populate/getModelsMapForPopulate.js +9 -7
  19. package/lib/helpers/populate/getSchemaTypes.js +2 -1
  20. package/lib/helpers/populate/removeDeselectedForeignField.js +2 -1
  21. package/lib/helpers/query/cast$expr.js +16 -0
  22. package/lib/helpers/query/castUpdate.js +5 -3
  23. package/lib/helpers/query/sanitizeFilter.js +2 -1
  24. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  25. package/lib/helpers/update/castArrayFilters.js +6 -5
  26. package/lib/helpers/update/removeUnusedArrayFilters.js +4 -0
  27. package/lib/helpers/updateValidators.js +16 -2
  28. package/lib/index.js +7 -0
  29. package/lib/internal.js +4 -0
  30. package/lib/model.js +28 -12
  31. package/lib/mongoose.js +17 -3
  32. package/lib/query.js +74 -7
  33. package/lib/schema/array.js +4 -2
  34. package/lib/schema/bigint.js +2 -1
  35. package/lib/schema/boolean.js +2 -1
  36. package/lib/schema/buffer.js +10 -13
  37. package/lib/schema/date.js +2 -1
  38. package/lib/schema/documentArray.js +18 -10
  39. package/lib/schema/int32.js +2 -1
  40. package/lib/schema/number.js +2 -1
  41. package/lib/schema/string.js +2 -1
  42. package/lib/schema/subdocument.js +2 -1
  43. package/lib/schema/uuid.js +2 -1
  44. package/lib/schema.js +58 -40
  45. package/lib/schemaType.js +9 -2
  46. package/lib/types/array/methods/index.js +81 -3
  47. package/lib/types/map.js +8 -7
  48. package/lib/types/subdocument.js +5 -1
  49. package/lib/utils.js +8 -6
  50. package/package.json +3 -3
  51. package/types/expressions.d.ts +1 -1
  52. package/types/index.d.ts +3 -0
  53. package/types/models.d.ts +12 -4
  54. package/types/query.d.ts +1 -1
  55. package/types/schemaoptions.d.ts +7 -0
  56. package/types/utility.d.ts +117 -5
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ const getInheritedProperty = require('./getInheritedProperty');
3
4
  const isMongooseArray = require('../types/array/isMongooseArray').isMongooseArray;
5
+ const isMongooseDocument = require('./isMongooseDocument');
4
6
  /**
5
7
  * Returns if `v` is a mongoose object that has a `toObject()` method we can use.
6
8
  *
@@ -14,9 +16,9 @@ module.exports = function(v) {
14
16
  return (
15
17
  v != null && (
16
18
  isMongooseArray(v) || // Array or Document Array
17
- v.$__ != null || // Document
18
- v.isMongooseBuffer || // Buffer
19
- v.$isMongooseMap // Map
19
+ isMongooseDocument(v) || // Document
20
+ (v.isMongooseBuffer && Buffer.isBuffer(v)) || // Buffer
21
+ (v.$isMongooseMap && getInheritedProperty(v, '$isMongooseMap')) // Map
20
22
  )
21
23
  );
22
24
  };
@@ -5,6 +5,7 @@ const applyBuiltinPlugins = require('../schema/applyBuiltinPlugins');
5
5
  const clone = require('../clone');
6
6
  const defineKey = require('../document/compile').defineKey;
7
7
  const get = require('../get');
8
+ const getOwnProperty = require('../getOwnProperty');
8
9
  const utils = require('../../utils');
9
10
  const mergeDiscriminatorSchema = require('../../helpers/discriminator/mergeDiscriminatorSchema');
10
11
 
@@ -15,7 +16,8 @@ const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = {
15
16
  id: true,
16
17
  virtuals: true,
17
18
  methods: true,
18
- statics: true
19
+ statics: true,
20
+ defaultSort: true
19
21
  };
20
22
 
21
23
  /**
@@ -71,6 +73,10 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
71
73
  if (!schema?.instanceOfSchema) {
72
74
  throw new Error('You must pass a valid discriminator Schema');
73
75
  }
76
+ // Discriminators are stored in POJOs keyed by name, so `__proto__` would change their prototype
77
+ if (name === '__proto__') {
78
+ throw new Error('Discriminator name "__proto__" is not allowed');
79
+ }
74
80
 
75
81
  mergeHooks = mergeHooks == null ? true : mergeHooks;
76
82
 
@@ -173,7 +179,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
173
179
  for (const conflictingPath of conflictingPaths) {
174
180
  delete schema.paths[conflictingPath];
175
181
  }
176
- schema._pathsWithDefaults = null;
182
+ schema._defaultsCache = null;
177
183
  schema._pathsWithTransforms = undefined;
178
184
  schema._hasSelectedPaths = undefined;
179
185
 
@@ -260,7 +266,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
260
266
 
261
267
  model.schema.discriminators[name] = schema;
262
268
 
263
- if (model.discriminators[name] && !schema.options.overwriteModels && !overwriteExisting) {
269
+ if (getOwnProperty(model.discriminators, name) && !schema.options.overwriteModels && !overwriteExisting) {
264
270
  throw new Error('Discriminator with name "' + name + '" already exists');
265
271
  }
266
272
 
@@ -9,7 +9,7 @@ module.exports = parallelLimit;
9
9
  */
10
10
 
11
11
  async function parallelLimit(params, fn, limit) {
12
- if (limit <= 0) {
12
+ if (!(limit > 0)) {
13
13
  throw new Error('Limit must be positive');
14
14
  }
15
15
 
@@ -19,43 +19,63 @@ async function parallelLimit(params, fn, limit) {
19
19
  }
20
20
 
21
21
  const results = new Array(length);
22
- // Fast path: there's nothing to bound, so kick everything off and wait once.
23
- // Avoids the per-task `Set` + `Promise.race` bookkeeping of a sliding window.
22
+ // Fast path: there's nothing to bound, so kick everything off and wait once
23
+ // instead of running the worker pool below.
24
24
  if (limit >= length) {
25
25
  for (let i = 0; i < length; ++i) {
26
- results[i] = fn(params[i], i);
26
+ try {
27
+ results[i] = fn(params[i], i);
28
+ } catch (err) {
29
+ // Stop launching, but still hand the calls already in flight to
30
+ // `Promise.all()` so a later rejection from one of them is handled.
31
+ results[i] = Promise.reject(err);
32
+ results.length = i + 1;
33
+ break;
34
+ }
27
35
  }
28
36
  return Promise.all(results);
29
37
  }
30
38
 
31
39
  let nextIndex = 0;
40
+ let hasError = false;
32
41
  let firstError = null;
33
42
 
34
43
  function worker() {
35
- if (nextIndex >= length || firstError !== null) {
44
+ if (nextIndex >= length || hasError) {
36
45
  return undefined;
37
46
  }
38
47
  const index = nextIndex++;
39
- return Promise.resolve(fn(params[index], index)).then(
48
+ let promise;
49
+ try {
50
+ promise = Promise.resolve(fn(params[index], index));
51
+ } catch (err) {
52
+ if (!hasError) {
53
+ hasError = true;
54
+ firstError = err;
55
+ }
56
+ return undefined;
57
+ }
58
+ return promise.then(
40
59
  (val) => {
41
60
  results[index] = val;
42
61
  return worker();
43
62
  },
44
63
  (err) => {
45
- if (firstError === null) {
64
+ if (!hasError) {
65
+ hasError = true;
46
66
  firstError = err;
47
67
  }
48
68
  }
49
69
  );
50
70
  }
51
71
 
52
- const workers = new Array(Math.min(limit, length));
53
- for (let i = 0; i < workers.length; ++i) {
54
- workers[i] = worker();
72
+ const workers = [];
73
+ for (let i = 0; i < limit; ++i) {
74
+ workers.push(worker());
55
75
  }
56
76
  await Promise.all(workers);
57
77
 
58
- if (firstError !== null) {
78
+ if (hasError) {
59
79
  throw firstError;
60
80
  }
61
81
  return results;
@@ -4,8 +4,10 @@ const MongooseMap = require('../../types/map');
4
4
  const SkipPopulateValue = require('./skipPopulateValue');
5
5
  const assignRawDocsToIdStructure = require('./assignRawDocsToIdStructure');
6
6
  const get = require('../get');
7
+ const getInheritedProperty = require('../getInheritedProperty');
7
8
  const getVirtual = require('./getVirtual');
8
9
  const leanPopulateMap = require('./leanPopulateMap');
10
+ const isMongooseDocument = require('../isMongooseDocument');
9
11
  const lookupLocalFields = require('./lookupLocalFields');
10
12
  const markArraySubdocsPopulated = require('./markArraySubdocsPopulated');
11
13
  const mpath = require('mpath');
@@ -110,7 +112,7 @@ module.exports = function assignVals(o) {
110
112
  // If we're populating a map, the existing value will be an object, so
111
113
  // we need to transform again
112
114
  const originalSchema = o.originalModel.schema;
113
- const isDoc = get(docs[i], '$__', null) != null;
115
+ const isDoc = isMongooseDocument(docs[i]);
114
116
  let isMap = isDoc ?
115
117
  existingVal instanceof Map :
116
118
  utils.isPOJO(existingVal);
@@ -129,11 +131,11 @@ module.exports = function assignVals(o) {
129
131
 
130
132
  if (isDoc && Array.isArray(valueToSet)) {
131
133
  for (const val of valueToSet) {
132
- if (val?.$__ != null) {
134
+ if (isMongooseDocument(val)) {
133
135
  val.$__.parent = docs[i];
134
136
  }
135
137
  }
136
- } else if (isDoc && valueToSet?.$__ != null) {
138
+ } else if (isDoc && isMongooseDocument(valueToSet)) {
137
139
  valueToSet.$__.parent = docs[i];
138
140
  }
139
141
 
@@ -196,11 +198,11 @@ module.exports = function assignVals(o) {
196
198
  break;
197
199
  }
198
200
  }
199
- if (docs[i].$__) {
201
+ if (isDoc) {
200
202
  o.allOptions.options[populateModelSymbol] = o.allOptions.model;
201
203
  docs[i].$populated(_path, o.unpopulatedValues[i], o.allOptions.options);
202
204
 
203
- if (valueToSet?.$__ != null) {
205
+ if (isMongooseDocument(valueToSet)) {
204
206
  valueToSet.$__.wasPopulated = { value: o.unpopulatedValues[i] };
205
207
  }
206
208
 
@@ -214,7 +216,7 @@ module.exports = function assignVals(o) {
214
216
  // underneath an array. See gh-6867
215
217
  mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false);
216
218
 
217
- if (docs[i].$__) {
219
+ if (isDoc) {
218
220
  markArraySubdocsPopulated(docs[i], [o.allOptions.options]);
219
221
  }
220
222
  }
@@ -354,7 +356,7 @@ function isPopulatedObject(obj) {
354
356
  }
355
357
 
356
358
  return Array.isArray(obj) ||
357
- obj.$isMongooseMap ||
358
- obj.$__ != null ||
359
+ getInheritedProperty(obj, '$isMongooseMap') ||
360
+ isMongooseDocument(obj) ||
359
361
  leanPopulateMap.has(obj);
360
362
  }
@@ -7,8 +7,10 @@ const get = require('../get');
7
7
  const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
8
8
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
9
9
  const getConstructorName = require('../getConstructorName');
10
+ const getOwnProperty = require('../getOwnProperty');
10
11
  const getSchemaTypes = require('./getSchemaTypes');
11
12
  const getVirtual = require('./getVirtual');
13
+ const isMongooseDocument = require('../isMongooseDocument');
12
14
  const lookupLocalFields = require('./lookupLocalFields');
13
15
  const mpath = require('mpath');
14
16
  const modelNamesFromRefPath = require('./modelNamesFromRefPath');
@@ -60,14 +62,14 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
60
62
  doc = docs[i];
61
63
  let justOne = null;
62
64
 
63
- if (doc.$__ != null && doc.populated(options.path)) {
65
+ if (isMongooseDocument(doc) && doc.populated(options.path)) {
64
66
  const forceRepopulate = options.forceRepopulate ?? doc.constructor.base.options.forceRepopulate;
65
67
  if (forceRepopulate === false) {
66
68
  continue;
67
69
  }
68
70
  }
69
71
 
70
- const docSchema = doc?.$__ != null ? doc.$__schema : modelSchema;
72
+ const docSchema = isMongooseDocument(doc) ? doc.$__schema : modelSchema;
71
73
  schema = getSchemaTypes(model, docSchema, doc, options.path, parts);
72
74
 
73
75
  // Special case: populating a path that's a DocumentArray unless
@@ -650,7 +652,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
650
652
  ids = matchIdsToRefPaths(ret, modelNamesForRefPath, modelName);
651
653
  }
652
654
 
653
- if (!available[modelName]) {
655
+ if (!getOwnProperty(available, modelName)) {
654
656
  const currentOptions = {
655
657
  model: Model
656
658
  };
@@ -700,7 +702,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
700
702
 
701
703
  function _getModelFromConn(conn, modelName) {
702
704
  /* If this connection has a parent from `useDb()`, bubble up to parent's models */
703
- if (conn.models[modelName] == null && conn._parent != null) {
705
+ if (getOwnProperty(conn.models, modelName) == null && conn._parent != null) {
704
706
  return _getModelFromConn(conn._parent, modelName);
705
707
  }
706
708
 
@@ -752,7 +754,7 @@ function _getLocalFieldValues(doc, localField, model, options, virtual, schema)
752
754
  _populateOptions.getters :
753
755
  get(virtual, 'options.getters', false);
754
756
  if (localFieldGetters.length !== 0 && getters) {
755
- const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc);
757
+ const hydratedDoc = isMongooseDocument(doc) ? doc : model.hydrate(doc);
756
758
  const localFieldValue = utils.getValue(localField, doc);
757
759
  if (Array.isArray(localFieldValue)) {
758
760
  const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc);
@@ -776,7 +778,7 @@ function _getLocalFieldValues(doc, localField, model, options, virtual, schema)
776
778
  */
777
779
 
778
780
  function convertTo_id(val, schema) {
779
- if (val?.$__ != null) {
781
+ if (isMongooseDocument(val)) {
780
782
  return val._doc._id;
781
783
  }
782
784
  if (val?._id != null && !schema?.$isSchemaMap) {
@@ -786,7 +788,7 @@ function convertTo_id(val, schema) {
786
788
  if (Array.isArray(val)) {
787
789
  const rawVal = val.__array ?? val;
788
790
  for (let i = 0; i < rawVal.length; ++i) {
789
- if (rawVal[i]?.$__ != null) {
791
+ if (isMongooseDocument(rawVal[i])) {
790
792
  rawVal[i] = rawVal[i]._doc._id;
791
793
  }
792
794
  }
@@ -7,6 +7,7 @@
7
7
  const Mixed = require('../../schema/mixed');
8
8
  const get = require('../get');
9
9
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
10
+ const isMongooseDocument = require('../isMongooseDocument');
10
11
  const leanPopulateMap = require('./leanPopulateMap');
11
12
  const mpath = require('mpath');
12
13
 
@@ -178,7 +179,7 @@ module.exports = function getSchemaTypes(model, schema, doc, path, parts) {
178
179
  }
179
180
 
180
181
  const fullPath = nestedPath.concat([trypath]).join('.');
181
- if (topLevelDoc?.$__ && topLevelDoc.$populated(fullPath, true) && p < parts.length) {
182
+ if (isMongooseDocument(topLevelDoc) && topLevelDoc.$populated(fullPath, true) && p < parts.length) {
182
183
  const model = topLevelDoc.$populated(fullPath, true).options[populateModelSymbol];
183
184
  if (model != null) {
184
185
  const ret = search(
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const get = require('../get');
4
+ const isMongooseDocument = require('../isMongooseDocument');
4
5
  const mpath = require('mpath');
5
6
  const parseProjection = require('../projection/parseProjection');
6
7
 
@@ -21,7 +22,7 @@ module.exports = function removeDeselectedForeignField(foreignFields, options, d
21
22
  }
22
23
 
23
24
  for (const val of docs) {
24
- if (val.$__ != null) {
25
+ if (isMongooseDocument(val)) {
25
26
  mpath.unset(foreignField, val._doc);
26
27
  } else {
27
28
  mpath.unset(foreignField, val);
@@ -3,6 +3,7 @@
3
3
  const CastError = require('../../error/cast');
4
4
  const StrictModeError = require('../../error/strict');
5
5
  const castNumber = require('../../cast/number');
6
+ const isPOJO = require('../isPOJO');
6
7
  const omitUndefined = require('../omitUndefined');
7
8
 
8
9
  const booleanComparison = new Set(['$and', '$or']);
@@ -181,6 +182,21 @@ function castIn(val, schema, strictQuery) {
181
182
  throw new Error('Path must be an array for $in');
182
183
  }
183
184
 
185
+ // The search value may be an expression, like '$field' or { $add: [...] }.
186
+ // Documents and buffers have `$` keys too, so they are still cast below.
187
+ if (!isLiteral(search) && (typeof search === 'string' || isPOJO(search))) {
188
+ return [
189
+ _castExpression(search, schema, strictQuery),
190
+ path
191
+ ];
192
+ }
193
+ if (typeof search === 'object' && search != null && search.$literal != null) {
194
+ return [
195
+ { $literal: schematype.embeddedSchemaType.cast(search.$literal) },
196
+ path
197
+ ];
198
+ }
199
+
184
200
  return [
185
201
  schematype.embeddedSchemaType.cast(search),
186
202
  path
@@ -11,7 +11,9 @@ const getConstructorName = require('../getConstructorName');
11
11
  const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
12
12
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
13
13
  const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath');
14
+ const getOwnProperty = require('../getOwnProperty');
14
15
  const handleImmutable = require('./handleImmutable');
16
+ const isMongooseDocument = require('../isMongooseDocument');
15
17
  const isOperator = require('./isOperator');
16
18
  const moveImmutableProperties = require('../update/moveImmutableProperties');
17
19
  const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
@@ -100,7 +102,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
100
102
  moveImmutableProperties(schema, obj, context);
101
103
  }
102
104
 
103
- if (obj?.$__ && typeof obj.toObject === 'function') {
105
+ if (isMongooseDocument(obj) && typeof obj.toObject === 'function') {
104
106
  obj = obj.toObject(internalToObjectOptions);
105
107
  }
106
108
 
@@ -139,7 +141,7 @@ module.exports = function castUpdate(schema, obj, options, context, filter) {
139
141
  const op = ops[i];
140
142
  val = ret[op];
141
143
  hasDollarKey = hasDollarKey || op.startsWith('$');
142
- if (val?.$__) {
144
+ if (isMongooseDocument(val)) {
143
145
  val = val.toObject(internalToObjectOptions);
144
146
  ret[op] = val;
145
147
  }
@@ -449,7 +451,7 @@ function walkUpdatePath(schema, obj, op, options, context, filter, prefix) {
449
451
  if (skip) {
450
452
  // Even if strict is `throw`, avoid throwing an error because of
451
453
  // virtuals because of #6731
452
- if (isStrict === 'throw' && schema.virtuals[checkPath] == null) {
454
+ if (isStrict === 'throw' && getOwnProperty(schema.virtuals, checkPath) == null) {
453
455
  throw new StrictModeError(prefix + key);
454
456
  } else {
455
457
  delete obj[key];
@@ -2,6 +2,7 @@
2
2
 
3
3
  const MongooseError = require('../../error/mongooseError');
4
4
  const hasDollarKeys = require('./hasDollarKeys');
5
+ const { logicalOperators } = require('../../filters/operators');
5
6
  const { trustedSymbol } = require('./trusted');
6
7
 
7
8
  module.exports = function sanitizeFilter(filter) {
@@ -21,7 +22,7 @@ module.exports = function sanitizeFilter(filter) {
21
22
  if (value?.[trustedSymbol]) {
22
23
  continue;
23
24
  }
24
- if (key === '$and' || key === '$or' || key === '$nor') {
25
+ if (logicalOperators.has(key)) {
25
26
  sanitizeFilter(value);
26
27
  continue;
27
28
  } else if (key[0] === '$') {
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Returns the handler for query operator `$conditional` from `handlers`, a
5
+ * SchemaType's `$conditionalHandlers`. Looks through `handlers`' full
6
+ * prototype chain, so custom SchemaTypes can build handlers with
7
+ * `Object.create(SchemaType.prototype.$conditionalHandlers)`, but stops at
8
+ * `Object.prototype` so keys like `valueOf` or `toString` aren't handlers.
9
+ *
10
+ * @param {object} handlers
11
+ * @param {string} $conditional
12
+ * @return {Function|undefined}
13
+ * @api private
14
+ */
15
+
16
+ module.exports = function getConditionalHandler(handlers, $conditional) {
17
+ for (let obj = handlers; obj != null && obj !== Object.prototype; obj = Object.getPrototypeOf(obj)) {
18
+ if (Object.hasOwn(obj, $conditional)) {
19
+ return obj[$conditional];
20
+ }
21
+ }
22
+ return undefined;
23
+ };
@@ -3,7 +3,9 @@
3
3
  const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
4
4
  const castFilterPath = require('../query/castFilterPath');
5
5
  const cleanPositionalOperators = require('../schema/cleanPositionalOperators');
6
+ const getOwnProperty = require('../getOwnProperty');
6
7
  const getPath = require('../schema/getPath');
8
+ const { logicalOperators } = require('../../filters/operators');
7
9
  const updatedPathsByArrayFilter = require('./updatedPathsByArrayFilter');
8
10
  const utils = require('../../utils');
9
11
 
@@ -74,7 +76,7 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
74
76
  // so recurse into each of them and cast the remaining keys as fields.
75
77
  const fieldKeys = [];
76
78
  for (const key of keys) {
77
- if (key === '$and' || key === '$or' || key === '$nor') {
79
+ if (logicalOperators.has(key)) {
78
80
  _castArrayFilters(filter[key], schema, strictQuery, updatedPathsByFilter, query);
79
81
  } else if (key.charAt(0) !== '$') {
80
82
  // $comment allowed here but we should not cast $comment. MongoDB server 9.x
@@ -90,12 +92,11 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
90
92
  const firstKey = fieldKeys[0];
91
93
  const dot = firstKey.indexOf('.');
92
94
  const filterWildcardPath = dot === -1 ? firstKey : firstKey.substring(0, dot);
93
- if (updatedPathsByFilter[filterWildcardPath] == null) {
95
+ const updatedPath = getOwnProperty(updatedPathsByFilter, filterWildcardPath);
96
+ if (updatedPath == null) {
94
97
  continue;
95
98
  }
96
- const baseFilterPath = cleanPositionalOperators(
97
- updatedPathsByFilter[filterWildcardPath]
98
- );
99
+ const baseFilterPath = cleanPositionalOperators(updatedPath);
99
100
 
100
101
  const baseSchematype = getPath(schema, baseFilterPath, discriminatorValueMap);
101
102
  let filterBaseSchema = baseSchematype != null ? baseSchematype.schema : null;
@@ -22,6 +22,10 @@ module.exports = function removeUnusedArrayFilters(update, options) {
22
22
 
23
23
  function _checkSingleFilterKey(arrayFilter, updateKeys) {
24
24
  const firstKey = Object.keys(arrayFilter)[0];
25
+ // Keep empty filters so MongoDB reports the error
26
+ if (firstKey == null) {
27
+ return true;
28
+ }
25
29
 
26
30
  if (firstKey === '$and' || firstKey === '$or') {
27
31
  if (!Array.isArray(arrayFilter[firstKey])) {
@@ -6,6 +6,7 @@
6
6
 
7
7
  const cleanPositionalOperators = require('./schema/cleanPositionalOperators');
8
8
  const flatten = require('./common').flatten;
9
+ const isMongooseDocument = require('./isMongooseDocument');
9
10
 
10
11
  /**
11
12
  * Applies validators and defaults to update and findOneAndUpdate operations,
@@ -89,7 +90,7 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
89
90
  if (schemaPath == null) {
90
91
  continue;
91
92
  }
92
- if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) {
93
+ if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i] && isUnderneathMixed(schema, updates[i])) {
93
94
  continue;
94
95
  }
95
96
  if (isPull[updates[i]] && schemaPath.$isMongooseArray) {
@@ -110,7 +111,7 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
110
111
  continue;
111
112
  }
112
113
 
113
- if (schemaPath.$isMongooseDocumentArrayElement && v?.$__ != null) {
114
+ if (schemaPath.$isMongooseDocumentArrayElement && isMongooseDocument(v)) {
114
115
  alreadyValidated ??= new Set();
115
116
  alreadyValidated.add(updates[i]);
116
117
  validatorsToExecute.push(
@@ -192,3 +193,16 @@ function hasValidatedAncestor(alreadyValidated, path) {
192
193
  }
193
194
  return false;
194
195
  }
196
+
197
+ /*!
198
+ * Returns true if the parent of `path` is a Mixed path, so `path` is a key
199
+ * inside a Mixed value rather than a path in the schema.
200
+ */
201
+
202
+ function isUnderneathMixed(schema, path) {
203
+ const lastDot = path.lastIndexOf('.');
204
+ if (lastDot === -1) {
205
+ return false;
206
+ }
207
+ return schema._getSchema(path.slice(0, lastDot))?.instance === 'Mixed';
208
+ }
package/lib/index.js CHANGED
@@ -12,6 +12,13 @@ const mongoose = require('./mongoose');
12
12
 
13
13
  mongoose.setDriver(mongodbDriver);
14
14
 
15
+ /**
16
+ * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
17
+ *
18
+ * @property mongo
19
+ * @api public
20
+ */
21
+
15
22
  mongoose.Mongoose.prototype.mongo = require('mongodb');
16
23
 
17
24
  module.exports = mongoose;
package/lib/internal.js CHANGED
@@ -13,6 +13,10 @@ function InternalCache() {
13
13
  this.activePaths = new ActiveRoster();
14
14
  }
15
15
 
16
+ // Spread documents (`{ ...doc }`) copy the document's `$__`, so `clone()` and
17
+ // `handleSpreadDoc()` check for this property on the prototype to tell them apart
18
+ // from user data with a `$__` key. Older Mongoose versions also define it, so
19
+ // spread documents from a different copy of Mongoose still count.
16
20
  InternalCache.prototype.strictMode = true;
17
21
 
18
22
  InternalCache.prototype.fullPath = undefined;