mongoose 9.12.3 → 9.13.1

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 (57) hide show
  1. package/lib/aggregate.js +4 -0
  2. package/lib/cast.js +4 -2
  3. package/lib/connection.js +10 -7
  4. package/lib/defaults/schemaDefaultsCache.js +62 -0
  5. package/lib/document.js +68 -52
  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/castUpdate.js +5 -3
  22. package/lib/helpers/query/sanitizeFilter.js +2 -1
  23. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  24. package/lib/helpers/update/castArrayFilters.js +6 -5
  25. package/lib/helpers/update/removeUnusedArrayFilters.js +4 -0
  26. package/lib/helpers/updateValidators.js +5 -4
  27. package/lib/index.js +7 -0
  28. package/lib/internal.js +4 -0
  29. package/lib/model.js +28 -14
  30. package/lib/mongoose.js +17 -3
  31. package/lib/options/schemaArrayOptions.js +13 -2
  32. package/lib/query.js +74 -7
  33. package/lib/schema/array.js +17 -13
  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 +16 -9
  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 +88 -41
  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 +2 -2
  51. package/types/models.d.ts +12 -4
  52. package/types/pipelinestage.d.ts +4 -2
  53. package/types/query.d.ts +1 -1
  54. package/types/schemaoptions.d.ts +7 -0
  55. package/types/utility.d.ts +117 -5
  56. package/tstyche.json +0 -7
  57. package/tstyche.matrix.json +0 -9
@@ -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);
@@ -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,
@@ -97,10 +98,10 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
97
98
  }
98
99
 
99
100
  if (v && Array.isArray(v.$in)) {
100
- v.$in.forEach((v, i) => {
101
+ v.$in.forEach((value, index) => {
101
102
  validatorsToExecute.push(
102
- schemaPath.doValidate(v, context, { updateValidator: true }).catch(err => {
103
- err.path = updates[i] + '.$in.' + i;
103
+ schemaPath.doValidate(value, context, { updateValidator: true }).catch(err => {
104
+ err.path = updates[i] + '.$in.' + index;
104
105
  validationErrors.push(err);
105
106
  })
106
107
  );
@@ -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(
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;
package/lib/model.js CHANGED
@@ -49,7 +49,9 @@ const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchema
49
49
  const discriminator = require('./helpers/model/discriminator');
50
50
  const each = require('./helpers/each');
51
51
  const get = require('./helpers/get');
52
+ const getOwnProperty = require('./helpers/getOwnProperty');
52
53
  const getConstructorName = require('./helpers/getConstructorName');
54
+ const isMongooseDocument = require('./helpers/isMongooseDocument');
53
55
  const getDiscriminatorByKey = require('./helpers/discriminator/getDiscriminatorByKey');
54
56
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
55
57
  const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate');
@@ -952,8 +954,10 @@ Model.exists = function exists(filter, options) {
952
954
  throw new MongooseError('Model.exists() no longer accepts a callback');
953
955
  }
954
956
 
957
+ // Which document matches doesn't matter, and a `defaultSort` would make MongoDB find every match.
955
958
  const query = this.findOne(filter).
956
959
  select({ _id: 1 }).
960
+ sort(null).
957
961
  lean().
958
962
  setOptions(options);
959
963
 
@@ -1024,7 +1028,7 @@ Model.discriminator = function(name, schema, options) {
1024
1028
  }
1025
1029
 
1026
1030
  schema = discriminator(this, name, schema, value, mergePlugins, options.mergeHooks, overwriteModels);
1027
- if (this.db.models[name] && !schema.options.overwriteModels && !overwriteModels) {
1031
+ if (getOwnProperty(this.db.models, name) && !schema.options.overwriteModels && !overwriteModels) {
1028
1032
  throw new OverwriteModelError(name);
1029
1033
  }
1030
1034
 
@@ -2140,6 +2144,8 @@ Model.find = function find(conditions, projection, options) {
2140
2144
  * Finds documents and counts the number of documents matching the filter.
2141
2145
  *
2142
2146
  * This function fires both `find` and `countDocuments` middleware.
2147
+ * Requires `options.limit`, and requires `options.sort` unless the schema has a [`defaultSort`](https://mongoosejs.com/docs/guide.html#defaultSort).
2148
+ * Throws if `options.sort` is empty, like `sort: null`.
2143
2149
  *
2144
2150
  * #### Example:
2145
2151
  *
@@ -2165,14 +2171,20 @@ Model.findAndCount = async function findAndCount(conditions, projection, options
2165
2171
  if (options == null) {
2166
2172
  throw new MongooseError('Model.findAndCount() requires an `options` argument with `sort` and `limit`');
2167
2173
  }
2168
- if (options.sort == null) {
2174
+ const findQuery = this.find(conditions, projection, options);
2175
+ if (options.sort == null && !this.schema.options.defaultSort) {
2169
2176
  throw new MongooseError('Model.findAndCount() requires `options.sort`');
2170
2177
  }
2178
+ // `sort: null`, `sort: undefined`, and `sort: {}` all mean "no sort".
2179
+ // This catches explicitly setting `sort: null`, `sort: undefined`, or
2180
+ // `sort: {}` in `options`.
2181
+ if (utils.isEmptyObject(findQuery.options.sort)) {
2182
+ throw new MongooseError('Model.findAndCount() does not allow an empty `options.sort`, like `sort: null`. Omit `options.sort` to use the schema\'s `defaultSort`.');
2183
+ }
2171
2184
  if (options.limit == null) {
2172
2185
  throw new MongooseError('Model.findAndCount() requires `options.limit`');
2173
2186
  }
2174
2187
 
2175
- const findQuery = this.find(conditions, projection, options);
2176
2188
  const countQuery = findQuery.clone().countDocuments().skip(0).limit(null);
2177
2189
 
2178
2190
  return Promise.all([findQuery.exec(), countQuery.exec()]);
@@ -3452,9 +3464,9 @@ function _setIsNew(doc, val, hasOnlyPrimitiveValues) {
3452
3464
  * @param {boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
3453
3465
  * @param {boolean} [options.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to any operations. Can be overridden at the operation-level.
3454
3466
  * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](https://mongoosejs.com/docs/transactions.html).
3455
- * @param {string|number} [options.w=1] The [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/). See [`Query#w()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.w()) for more information.
3467
+ * @param {string|number} [options.w] The [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/). If not set, the MongoDB server's default write concern applies. See [`Query#w()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.w()) for more information.
3456
3468
  * @param {number} [options.wtimeout=null] The [write concern timeout](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout).
3457
- * @param {boolean} [options.j=true] If false, disable [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option)
3469
+ * @param {boolean} [options.j] Set to true to request [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). If not set, the MongoDB server's default write concern applies.
3458
3470
  * @param {boolean} [options.skipValidation=false] Set to true to skip Mongoose schema validation on bulk write operations. Mongoose currently runs validation on `insertOne` and `replaceOne` operations by default.
3459
3471
  * @param {boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://www.mongodb.com/docs/manual/core/schema-validation/) for all writes in this bulk.
3460
3472
  * @param {boolean} [options.throwOnValidationError=false] If true and `ordered: false`, throw an error if one of the operations failed validation, but all valid operations completed successfully. Note that Mongoose will still send all valid operations to the MongoDB server.
@@ -3644,9 +3656,9 @@ async function _bulkWrite(ops, options) {
3644
3656
  * @param {object} [options] options passed to the underlying `bulkWrite()`
3645
3657
  * @param {boolean} [options.timestamps] defaults to `null`, when set to false, mongoose will not add/update timestamps to the documents.
3646
3658
  * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](https://mongoosejs.com/docs/transactions.html).
3647
- * @param {string|number} [options.w=1] The [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/). See [`Query#w()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.w()) for more information.
3659
+ * @param {string|number} [options.w] The [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/). If not set, the MongoDB server's default write concern applies. See [`Query#w()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.w()) for more information.
3648
3660
  * @param {number} [options.wtimeout=null] The [write concern timeout](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout).
3649
- * @param {boolean} [options.j=true] If false, disable [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option)
3661
+ * @param {boolean} [options.j] Set to true to request [journal acknowledgement](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). If not set, the MongoDB server's default write concern applies.
3650
3662
  * @param {boolean} [options.validateBeforeSave=true] set to `false` to skip Mongoose validation on all documents
3651
3663
  * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
3652
3664
  * @param {boolean} [options.middleware.pre=true] set to `false` to skip only pre hooks
@@ -3765,7 +3777,7 @@ Model.applyDefaults = function applyDefaults(doc) {
3765
3777
  if (doc == null) {
3766
3778
  return doc;
3767
3779
  }
3768
- if (doc.$__ != null) {
3780
+ if (isMongooseDocument(doc)) {
3769
3781
  applyDefaultsHelper(doc, doc.$__.fields, doc.$__.exclude);
3770
3782
 
3771
3783
  for (const subdoc of doc.$getAllSubdocs()) {
@@ -3805,7 +3817,7 @@ Model.applyVirtuals = function applyVirtuals(obj, virtualsToApply) {
3805
3817
  return obj;
3806
3818
  }
3807
3819
  // Nothing to do if this is already a hydrated document - it should already have virtuals
3808
- if (obj.$__ != null) {
3820
+ if (isMongooseDocument(obj)) {
3809
3821
  return obj;
3810
3822
  }
3811
3823
 
@@ -3840,7 +3852,7 @@ Model.applyTimestamps = function applyTimestamps(obj, options) {
3840
3852
  return obj;
3841
3853
  }
3842
3854
  // Nothing to do if this is already a hydrated document - it should already have timestamps
3843
- if (obj.$__ != null) {
3855
+ if (isMongooseDocument(obj)) {
3844
3856
  return obj;
3845
3857
  }
3846
3858
 
@@ -4080,7 +4092,7 @@ Model.buildBulkWriteOperations = function buildBulkWriteOperations(documents, op
4080
4092
  * @param {boolean} [options.setters=false] if true, apply schema setters when hydrating
4081
4093
  * @param {boolean} [options.hydratedPopulatedDocs=false] if true, populates the docs if passing pre-populated data
4082
4094
  * @param {boolean} [options.virtuals=false] if true, sets any virtuals present on `obj`
4083
- * @param {boolean|'throw'} [options.strict=false] configure strict mode for the hydrated document. In particular, if strict is false, fields not in the schema won't be stripped out; if strict is 'throw', `hydrate()` will throw an error if there are any fields that are not in the schema. Defaults to true (silently strip out fields not in the schema).
4095
+ * @param {boolean|'throw'} [options.strict] configure strict mode for the hydrated document. In particular, if strict is false, fields not in the schema won't be stripped out; if strict is 'throw', `hydrate()` will throw an error if there are any fields that are not in the schema. Falls back to the schema's [`strict` option](https://mongoosejs.com/docs/guide.html#strict) if this option is nullish, which is true by default (silently strip out fields not in the schema).
4084
4096
  * @return {Document} document instance
4085
4097
  * @api public
4086
4098
  */
@@ -4093,7 +4105,7 @@ Model.hydrate = function hydrate(obj, projection, options) {
4093
4105
  }
4094
4106
 
4095
4107
  if (projection != null) {
4096
- if (obj?.$__ != null) {
4108
+ if (isMongooseDocument(obj)) {
4097
4109
  obj = obj.toObject(internalToObjectOptions);
4098
4110
  }
4099
4111
  projection = parseProjection(projection);
@@ -4598,7 +4610,7 @@ async function _populatePath(model, docs, populateOptions) {
4598
4610
  }
4599
4611
 
4600
4612
  const modelsMap = getModelsMapForPopulate(model, docs, populateOptions);
4601
- if (modelsMap instanceof MongooseError) {
4613
+ if (modelsMap instanceof Error) {
4602
4614
  throw modelsMap;
4603
4615
  }
4604
4616
  const len = modelsMap.length;
@@ -4773,7 +4785,7 @@ async function _populatePath(model, docs, populateOptions) {
4773
4785
  // `utils.getValue()` rather than a bracket lookup, because `mod.options.path` may be
4774
4786
  // a dotted path like 'children.child', which a lean result does not store as a
4775
4787
  // single key.
4776
- const childVal = doc.$__ != null ? doc.get(mod.options.path) : utils.getValue(mod.options.path, doc);
4788
+ const childVal = isMongooseDocument(doc) ? doc.get(mod.options.path) : utils.getValue(mod.options.path, doc);
4777
4789
  if (Array.isArray(childVal)) {
4778
4790
  childDocsToPopulate.push(...childVal);
4779
4791
  } else if (childVal != null) {
@@ -4837,6 +4849,8 @@ function _execPopulateQuery(mod, match, select) {
4837
4849
 
4838
4850
  if (mod.count) {
4839
4851
  delete queryOptions.skip;
4852
+ // Sort doesn't affect the count, so skip the ref model's `defaultSort`
4853
+ queryOptions.sort ??= {};
4840
4854
  }
4841
4855
 
4842
4856
  if (queryOptions.perDocumentLimit != null) {