mongoose 9.12.3 → 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.
- package/lib/aggregate.js +4 -0
- package/lib/cast.js +4 -2
- package/lib/connection.js +10 -7
- package/lib/defaults/schemaDefaultsCache.js +62 -0
- package/lib/document.js +68 -52
- package/lib/filters/operators.js +8 -0
- package/lib/helpers/clone.js +9 -8
- package/lib/helpers/document/applyDefaults.js +1 -1
- package/lib/helpers/document/compile.js +2 -1
- package/lib/helpers/document/handleSpreadDoc.js +2 -1
- package/lib/helpers/getInheritedProperty.js +28 -0
- package/lib/helpers/getOwnProperty.js +19 -0
- package/lib/helpers/isMongooseDocument.js +24 -0
- package/lib/helpers/isMongooseObject.js +5 -3
- package/lib/helpers/model/discriminator.js +9 -3
- package/lib/helpers/parallelLimit.js +31 -11
- package/lib/helpers/populate/assignVals.js +10 -8
- package/lib/helpers/populate/getModelsMapForPopulate.js +9 -7
- package/lib/helpers/populate/getSchemaTypes.js +2 -1
- package/lib/helpers/populate/removeDeselectedForeignField.js +2 -1
- package/lib/helpers/query/castUpdate.js +5 -3
- package/lib/helpers/query/sanitizeFilter.js +2 -1
- package/lib/helpers/schematype/getConditionalHandler.js +23 -0
- package/lib/helpers/update/castArrayFilters.js +6 -5
- package/lib/helpers/update/removeUnusedArrayFilters.js +4 -0
- package/lib/helpers/updateValidators.js +2 -1
- package/lib/index.js +7 -0
- package/lib/internal.js +4 -0
- package/lib/model.js +24 -10
- package/lib/mongoose.js +17 -3
- package/lib/query.js +74 -7
- package/lib/schema/array.js +4 -2
- package/lib/schema/bigint.js +2 -1
- package/lib/schema/boolean.js +2 -1
- package/lib/schema/buffer.js +10 -13
- package/lib/schema/date.js +2 -1
- package/lib/schema/documentArray.js +16 -9
- package/lib/schema/int32.js +2 -1
- package/lib/schema/number.js +2 -1
- package/lib/schema/string.js +2 -1
- package/lib/schema/subdocument.js +2 -1
- package/lib/schema/uuid.js +2 -1
- package/lib/schema.js +58 -40
- package/lib/schemaType.js +9 -2
- package/lib/types/array/methods/index.js +81 -3
- package/lib/types/map.js +8 -7
- package/lib/types/subdocument.js +5 -1
- package/lib/utils.js +8 -6
- package/package.json +2 -2
- package/types/models.d.ts +12 -4
- package/types/query.d.ts +1 -1
- package/types/schemaoptions.d.ts +7 -0
- package/types/utility.d.ts +117 -5
package/lib/schema.js
CHANGED
|
@@ -8,6 +8,7 @@ const EventEmitter = require('events').EventEmitter;
|
|
|
8
8
|
const Kareem = require('kareem');
|
|
9
9
|
const MongooseError = require('./error/mongooseError');
|
|
10
10
|
const PathTrie = require('./helpers/pathTrie');
|
|
11
|
+
const SchemaDefaultsCache = require('./defaults/schemaDefaultsCache');
|
|
11
12
|
const SchemaType = require('./schemaType');
|
|
12
13
|
const SchemaTypeOptions = require('./options/schemaTypeOptions');
|
|
13
14
|
const VirtualOptions = require('./options/virtualOptions');
|
|
@@ -19,6 +20,7 @@ const getConstructorName = require('./helpers/getConstructorName');
|
|
|
19
20
|
const getIndexes = require('./helpers/schema/getIndexes');
|
|
20
21
|
const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenceAliases');
|
|
21
22
|
const idGetter = require('./helpers/schema/idGetter');
|
|
23
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
22
24
|
const isIndexSpecEqual = require('./helpers/indexes/isIndexSpecEqual');
|
|
23
25
|
const merge = require('./helpers/schema/merge');
|
|
24
26
|
const mpath = require('mpath');
|
|
@@ -91,6 +93,7 @@ const numberRE = /^\d+$/;
|
|
|
91
93
|
* - [collectionOptions]: object with options passed to [`createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/) when calling `Model.createCollection()` or `autoCreate` set to true.
|
|
92
94
|
* - [encryptionType]: the encryption type for the schema. Valid options are `csfle` or `queryableEncryption`. See https://mongoosejs.com/docs/field-level-encryption.html.
|
|
93
95
|
* - [lean]: boolean - set to true to make all queries use [lean](https://mongoosejs.com/docs/tutorials/lean.html) by default. Defaults to false.
|
|
96
|
+
* - [defaultSort](https://mongoosejs.com/docs/guide.html#defaultSort): string, object, array, or map - defaults to `undefined`. The sort to use for queries that don't specify a sort, like `find()`, `findOne()`, and `findOneAndUpdate()`. Does not apply to `updateOne()` and `replaceOne()` for compatibility with MongoDB < 8.0.
|
|
94
97
|
*
|
|
95
98
|
* #### Options for Nested Schemas:
|
|
96
99
|
*
|
|
@@ -647,6 +650,8 @@ Schema.prototype.defaultOptions = function(options) {
|
|
|
647
650
|
throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
|
|
648
651
|
}
|
|
649
652
|
|
|
653
|
+
_validateDefaultSort(options.defaultSort);
|
|
654
|
+
|
|
650
655
|
if (typeof options.read === 'string') {
|
|
651
656
|
options.read = handleReadPreferenceAliases(options.read);
|
|
652
657
|
} else if (Array.isArray(options.read) && typeof options.read[0] === 'string') {
|
|
@@ -1362,7 +1367,7 @@ Schema.prototype.path = function(path, obj) {
|
|
|
1362
1367
|
branch[last] = clone(obj);
|
|
1363
1368
|
|
|
1364
1369
|
this.paths[path] = this.interpretAsType(path, obj, this.options);
|
|
1365
|
-
this.
|
|
1370
|
+
this._defaultsCache = null;
|
|
1366
1371
|
this._hasSelectedPaths = undefined;
|
|
1367
1372
|
const schemaType = this.paths[path];
|
|
1368
1373
|
|
|
@@ -1929,47 +1934,21 @@ Schema.prototype.pathsWithTransforms = function pathsWithTransforms(invalidate)
|
|
|
1929
1934
|
};
|
|
1930
1935
|
|
|
1931
1936
|
/**
|
|
1932
|
-
* Returns the paths in this schema that have a default,
|
|
1933
|
-
*
|
|
1934
|
-
*
|
|
1935
|
-
*
|
|
1937
|
+
* Returns a `SchemaDefaultsCache` with the paths in this schema that have a default,
|
|
1938
|
+
* both for the whole schema and grouped by nested path. This lets `applyDefaults()`
|
|
1939
|
+
* and setting nested paths skip iterating over every path in the schema for every
|
|
1940
|
+
* document. Computed when the first document is created, and cleared when
|
|
1936
1941
|
* compiling or recompiling a model that uses this schema or if paths are added or removed.
|
|
1937
1942
|
*
|
|
1938
|
-
* #### Example:
|
|
1939
|
-
*
|
|
1940
|
-
* const s = new Schema({
|
|
1941
|
-
* name: { type: String, default: 'test' },
|
|
1942
|
-
* tags: [String],
|
|
1943
|
-
* notes: String
|
|
1944
|
-
* });
|
|
1945
|
-
* s._getPathsWithDefaults().paths; // [ 'name', 'tags', '_id' ]
|
|
1946
|
-
*
|
|
1947
1943
|
* @api private
|
|
1948
|
-
* @return {
|
|
1944
|
+
* @return {SchemaDefaultsCache}
|
|
1949
1945
|
*/
|
|
1950
1946
|
|
|
1951
|
-
Schema.prototype.
|
|
1952
|
-
if (this.
|
|
1953
|
-
|
|
1954
|
-
}
|
|
1955
|
-
|
|
1956
|
-
const paths = [];
|
|
1957
|
-
const schemaTypes = [];
|
|
1958
|
-
for (const path of Object.keys(this.paths)) {
|
|
1959
|
-
const schemaType = this.paths[path];
|
|
1960
|
-
if (schemaType.defaultValue === undefined) {
|
|
1961
|
-
continue;
|
|
1962
|
-
}
|
|
1963
|
-
const pieces = schemaType.splitPath();
|
|
1964
|
-
if (pieces[pieces.length - 1] === '$*') {
|
|
1965
|
-
continue;
|
|
1966
|
-
}
|
|
1967
|
-
paths.push(path);
|
|
1968
|
-
schemaTypes.push(schemaType);
|
|
1947
|
+
Schema.prototype._getDefaultsCache = function _getDefaultsCache() {
|
|
1948
|
+
if (this._defaultsCache == null) {
|
|
1949
|
+
this._defaultsCache = new SchemaDefaultsCache(this);
|
|
1969
1950
|
}
|
|
1970
|
-
|
|
1971
|
-
this._pathsWithDefaults = { paths, schemaTypes };
|
|
1972
|
-
return this._pathsWithDefaults;
|
|
1951
|
+
return this._defaultsCache;
|
|
1973
1952
|
};
|
|
1974
1953
|
|
|
1975
1954
|
/**
|
|
@@ -2742,13 +2721,13 @@ Schema.prototype.virtual = function(name, options) {
|
|
|
2742
2721
|
if (opts?.hydratedPopulatedDocs && !options.count) {
|
|
2743
2722
|
const modelNames = virtual._getModelNamesForPopulate(this);
|
|
2744
2723
|
const populatedVal = this.$$populatedVirtuals[name];
|
|
2745
|
-
if (!Array.isArray(populatedVal) && !populatedVal
|
|
2724
|
+
if (!Array.isArray(populatedVal) && !isMongooseDocument(populatedVal) && modelNames?.length === 1) {
|
|
2746
2725
|
const PopulateModel = this.db.model(modelNames[0]);
|
|
2747
2726
|
this.$$populatedVirtuals[name] = PopulateModel.hydrate(populatedVal);
|
|
2748
2727
|
} else if (Array.isArray(populatedVal) && modelNames?.length === 1) {
|
|
2749
2728
|
const PopulateModel = this.db.model(modelNames[0]);
|
|
2750
2729
|
for (let i = 0; i < populatedVal.length; ++i) {
|
|
2751
|
-
if (!populatedVal[i]
|
|
2730
|
+
if (!isMongooseDocument(populatedVal[i])) {
|
|
2752
2731
|
populatedVal[i] = PopulateModel.hydrate(populatedVal[i], null, { hydratedPopulatedDocs: true });
|
|
2753
2732
|
}
|
|
2754
2733
|
}
|
|
@@ -2874,7 +2853,7 @@ Schema.prototype.remove = function(path) {
|
|
|
2874
2853
|
if (this.path(name) == null && !this.nested[name]) {
|
|
2875
2854
|
return;
|
|
2876
2855
|
}
|
|
2877
|
-
this.
|
|
2856
|
+
this._defaultsCache = null;
|
|
2878
2857
|
this._hasSelectedPaths = undefined;
|
|
2879
2858
|
if (this.nested[name]) {
|
|
2880
2859
|
const allKeys = Object.keys(this.paths).
|
|
@@ -3299,12 +3278,51 @@ function isArrayFilter(piece) {
|
|
|
3299
3278
|
*/
|
|
3300
3279
|
|
|
3301
3280
|
Schema.prototype._preCompile = function _preCompile() {
|
|
3281
|
+
// Check `defaultSort` again in case it was changed after the schema was created
|
|
3282
|
+
_validateDefaultSort(this.options.defaultSort);
|
|
3302
3283
|
this.plugin(idGetter, { deduplicate: true });
|
|
3303
3284
|
_precomputeOptimisticConcurrency(this);
|
|
3304
3285
|
_clearDerivedPathCaches(this, new Set());
|
|
3305
3286
|
this._hasSelectedPaths = _hasSelectedPaths(this, []);
|
|
3306
3287
|
};
|
|
3307
3288
|
|
|
3289
|
+
/*!
|
|
3290
|
+
* Throws if `defaultSort` is not a valid value for the `defaultSort` schema option. Disallows `$meta` sorts,
|
|
3291
|
+
* like `{ score: { $meta: 'textScore' } }`, because MongoDB throws on `$meta` sorts for queries without `$text`.
|
|
3292
|
+
*/
|
|
3293
|
+
|
|
3294
|
+
function _validateDefaultSort(defaultSort) {
|
|
3295
|
+
if (!defaultSort) {
|
|
3296
|
+
return;
|
|
3297
|
+
}
|
|
3298
|
+
// An empty `defaultSort` would silently mean "no sort", which would let `findAndCount()` run unsorted.
|
|
3299
|
+
// Use `defaultSort: null` to disable the default sort instead.
|
|
3300
|
+
const emptyError = '`defaultSort` must not be empty, use `defaultSort: null` to disable the default sort';
|
|
3301
|
+
if (typeof defaultSort === 'string') {
|
|
3302
|
+
if (defaultSort.trim() === '') {
|
|
3303
|
+
throw new MongooseError(emptyError);
|
|
3304
|
+
}
|
|
3305
|
+
return;
|
|
3306
|
+
}
|
|
3307
|
+
if (typeof defaultSort !== 'object') {
|
|
3308
|
+
throw new MongooseError('`defaultSort` must be falsy, string, object, array, or Map, got `' + (typeof defaultSort) + '`');
|
|
3309
|
+
}
|
|
3310
|
+
const entries = defaultSort instanceof Map ?
|
|
3311
|
+
Array.from(defaultSort) :
|
|
3312
|
+
Array.isArray(defaultSort) ? defaultSort : Object.entries(defaultSort);
|
|
3313
|
+
if (entries.length === 0) {
|
|
3314
|
+
throw new MongooseError(emptyError);
|
|
3315
|
+
}
|
|
3316
|
+
for (const entry of entries) {
|
|
3317
|
+
if (!Array.isArray(entry)) {
|
|
3318
|
+
throw new MongooseError('`defaultSort` array must be an array of [key, value] arrays, like `[[\'name\', 1]]`');
|
|
3319
|
+
}
|
|
3320
|
+
if (entry[1] != null && Object.hasOwn(entry[1], '$meta')) {
|
|
3321
|
+
throw new MongooseError('`defaultSort` does not support `$meta` sorts, got `$meta` for `' + entry[0] + '`');
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3308
3326
|
/*!
|
|
3309
3327
|
* Clears caches that are derived from `schema.paths` on `schema` and all of its
|
|
3310
3328
|
* nested schemas, because nested schemas can change until the model is compiled.
|
|
@@ -3316,7 +3334,7 @@ function _clearDerivedPathCaches(schema, seen) {
|
|
|
3316
3334
|
}
|
|
3317
3335
|
seen.add(schema);
|
|
3318
3336
|
|
|
3319
|
-
schema.
|
|
3337
|
+
schema._defaultsCache = null;
|
|
3320
3338
|
schema._pathsWithTransforms = undefined;
|
|
3321
3339
|
for (const { schema: childSchema } of schema.childSchemas) {
|
|
3322
3340
|
_clearDerivedPathCaches(childSchema, seen);
|
package/lib/schemaType.js
CHANGED
|
@@ -9,8 +9,10 @@ const SchemaTypeOptions = require('./options/schemaTypeOptions');
|
|
|
9
9
|
const $exists = require('./schema/operators/exists');
|
|
10
10
|
const $type = require('./schema/operators/type');
|
|
11
11
|
const clone = require('./helpers/clone');
|
|
12
|
+
const getConditionalHandler = require('./helpers/schematype/getConditionalHandler');
|
|
12
13
|
const handleImmutable = require('./helpers/schematype/handleImmutable');
|
|
13
14
|
const isAsyncFunction = require('./helpers/isAsyncFunction');
|
|
15
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
14
16
|
const isSimpleValidator = require('./helpers/isSimpleValidator');
|
|
15
17
|
const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol;
|
|
16
18
|
const utils = require('./utils');
|
|
@@ -1706,7 +1708,7 @@ SchemaType.prototype._castRef = function _castRef(value, doc, init, options) {
|
|
|
1706
1708
|
return value;
|
|
1707
1709
|
}
|
|
1708
1710
|
|
|
1709
|
-
if (value
|
|
1711
|
+
if (isMongooseDocument(value)) {
|
|
1710
1712
|
value.$__.wasPopulated = value.$__.wasPopulated || { value: value._doc._id };
|
|
1711
1713
|
return value;
|
|
1712
1714
|
}
|
|
@@ -1814,7 +1816,7 @@ SchemaType.prototype.$conditionalHandlers = {
|
|
|
1814
1816
|
SchemaType.prototype.castForQuery = function($conditional, val, context) {
|
|
1815
1817
|
let handler;
|
|
1816
1818
|
if ($conditional != null) {
|
|
1817
|
-
handler = this.$conditionalHandlers
|
|
1819
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
1818
1820
|
if (!handler) {
|
|
1819
1821
|
throw new MongooseError('Can\'t use ' + $conditional);
|
|
1820
1822
|
}
|
|
@@ -1882,6 +1884,11 @@ SchemaType.prototype.clone = function() {
|
|
|
1882
1884
|
schematype.validators = this.validators.slice();
|
|
1883
1885
|
if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator;
|
|
1884
1886
|
if (this.allowNullValidator !== undefined) schematype.allowNullValidator = this.allowNullValidator;
|
|
1887
|
+
if (this.enumValidator !== undefined) schematype.enumValidator = this.enumValidator;
|
|
1888
|
+
if (this.minValidator !== undefined) schematype.minValidator = this.minValidator;
|
|
1889
|
+
if (this.maxValidator !== undefined) schematype.maxValidator = this.maxValidator;
|
|
1890
|
+
if (this.minlengthValidator !== undefined) schematype.minlengthValidator = this.minlengthValidator;
|
|
1891
|
+
if (this.maxlengthValidator !== undefined) schematype.maxlengthValidator = this.maxlengthValidator;
|
|
1885
1892
|
if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue;
|
|
1886
1893
|
if (this.$immutable !== undefined && this.options.immutable === undefined) {
|
|
1887
1894
|
schematype.$immutable = this.$immutable;
|
|
@@ -548,13 +548,23 @@ const methods = {
|
|
|
548
548
|
if (isBsonType(obj, 'ObjectId') || obj instanceof UUID) {
|
|
549
549
|
obj = obj.toString();
|
|
550
550
|
}
|
|
551
|
-
//
|
|
552
|
-
|
|
551
|
+
// `==` compares these by reference, or coerces them so they match other
|
|
552
|
+
// types, like `new Double(4.5) == 4.5`. Compare them by type and value instead.
|
|
553
|
+
let compare = null;
|
|
554
|
+
if (obj instanceof Date) {
|
|
555
|
+
compare = compareDate;
|
|
556
|
+
} else if (Buffer.isBuffer(obj)) {
|
|
557
|
+
compare = compareBuffer;
|
|
558
|
+
} else if (isBsonType(obj, 'Double')) {
|
|
559
|
+
compare = compareDouble;
|
|
560
|
+
} else if (isBsonType(obj, 'Decimal128')) {
|
|
561
|
+
compare = compareDecimal128;
|
|
562
|
+
}
|
|
553
563
|
|
|
554
564
|
fromIndex = fromIndex == null ? 0 : fromIndex;
|
|
555
565
|
const len = this.length;
|
|
556
566
|
for (let i = fromIndex; i < len; ++i) {
|
|
557
|
-
if (
|
|
567
|
+
if (compare === null ? obj == this[i] : compare(obj, this[i])) {
|
|
558
568
|
return i;
|
|
559
569
|
}
|
|
560
570
|
}
|
|
@@ -986,6 +996,74 @@ const methods = {
|
|
|
986
996
|
* ignore
|
|
987
997
|
*/
|
|
988
998
|
|
|
999
|
+
/**
|
|
1000
|
+
* Compare dates by timestamp like `addToSet()` does, so `pull()` works on date arrays.
|
|
1001
|
+
* @api private
|
|
1002
|
+
*/
|
|
1003
|
+
|
|
1004
|
+
function compareDate(obj, cur) {
|
|
1005
|
+
return cur instanceof Date && +obj === +cur;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* MongoDB stores a subtype with binary data, so equal bytes with different
|
|
1010
|
+
* subtypes are different values.
|
|
1011
|
+
* @api private
|
|
1012
|
+
*/
|
|
1013
|
+
|
|
1014
|
+
function compareBuffer(obj, cur) {
|
|
1015
|
+
return Buffer.isBuffer(cur) && (obj._subtype || 0) === (cur._subtype || 0) && obj.equals(cur);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Match Doubles only against other Doubles. MongoDB considers NaN equal to NaN.
|
|
1020
|
+
* @api private
|
|
1021
|
+
*/
|
|
1022
|
+
|
|
1023
|
+
function compareDouble(obj, cur) {
|
|
1024
|
+
if (!isBsonType(cur, 'Double')) {
|
|
1025
|
+
return false;
|
|
1026
|
+
}
|
|
1027
|
+
const a = obj.valueOf();
|
|
1028
|
+
const b = cur.valueOf();
|
|
1029
|
+
return a === b || (Number.isNaN(a) && Number.isNaN(b));
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const decimal128StringRE = /^(-?)(\d+)(?:\.(\d*))?(?:E([+-]\d+))?$/;
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Match Decimal128s only against other Decimal128s, by numeric value, like
|
|
1036
|
+
* MongoDB does: '1.50' matches '1.5', '1E+3' matches '1000', '-0' matches '0'.
|
|
1037
|
+
* @api private
|
|
1038
|
+
*/
|
|
1039
|
+
|
|
1040
|
+
function compareDecimal128(obj, cur) {
|
|
1041
|
+
if (!isBsonType(cur, 'Decimal128')) {
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
const a = obj.toString();
|
|
1045
|
+
const b = cur.toString();
|
|
1046
|
+
if (a === b) {
|
|
1047
|
+
return true;
|
|
1048
|
+
}
|
|
1049
|
+
const matchA = decimal128StringRE.exec(a);
|
|
1050
|
+
const matchB = decimal128StringRE.exec(b);
|
|
1051
|
+
if (matchA === null || matchB === null) {
|
|
1052
|
+
return false; // NaN and Infinity only match the same string
|
|
1053
|
+
}
|
|
1054
|
+
// `toString()` writes `coefficient * 10 ** exponent`, so compare coefficients
|
|
1055
|
+
// after scaling the one with the larger exponent down to the smaller exponent
|
|
1056
|
+
const fractionA = matchA[3] || '';
|
|
1057
|
+
const fractionB = matchB[3] || '';
|
|
1058
|
+
const coefficientA = BigInt(matchA[1] + matchA[2] + fractionA);
|
|
1059
|
+
const coefficientB = BigInt(matchB[1] + matchB[2] + fractionB);
|
|
1060
|
+
const exponentA = (+matchA[4] || 0) - fractionA.length;
|
|
1061
|
+
const exponentB = (+matchB[4] || 0) - fractionB.length;
|
|
1062
|
+
return exponentA > exponentB ?
|
|
1063
|
+
coefficientA * 10n ** BigInt(exponentA - exponentB) === coefficientB :
|
|
1064
|
+
coefficientB * 10n ** BigInt(exponentB - exponentA) === coefficientA;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
989
1067
|
function _isAllSubdocs(docs, ref) {
|
|
990
1068
|
if (!ref) {
|
|
991
1069
|
return false;
|
package/lib/types/map.js
CHANGED
|
@@ -7,6 +7,7 @@ const deepEqual = require('../utils').deepEqual;
|
|
|
7
7
|
const isMongooseArray = require('../utils').isMongooseArray;
|
|
8
8
|
const getConstructorName = require('../helpers/getConstructorName');
|
|
9
9
|
const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
|
|
10
|
+
const isMongooseDocument = require('../helpers/isMongooseDocument');
|
|
10
11
|
const util = require('util');
|
|
11
12
|
const specialProperties = require('../helpers/specialProperties');
|
|
12
13
|
const isBsonType = require('../helpers/isBsonType');
|
|
@@ -137,7 +138,7 @@ class MongooseMap extends Map {
|
|
|
137
138
|
}
|
|
138
139
|
if (Array.isArray(value) && this.$__schemaType.$isMongooseArray) {
|
|
139
140
|
value = value.map(v => {
|
|
140
|
-
if (v
|
|
141
|
+
if (!isMongooseDocument(v)) {
|
|
141
142
|
v = new populated.options[populateModelSymbol](v);
|
|
142
143
|
}
|
|
143
144
|
// Doesn't support single nested "in-place" populate
|
|
@@ -145,7 +146,7 @@ class MongooseMap extends Map {
|
|
|
145
146
|
return v;
|
|
146
147
|
});
|
|
147
148
|
} else if (value != null) {
|
|
148
|
-
if (value
|
|
149
|
+
if (!isMongooseDocument(value)) {
|
|
149
150
|
value = new populated.options[populateModelSymbol](value);
|
|
150
151
|
}
|
|
151
152
|
// Doesn't support single nested "in-place" populate
|
|
@@ -263,18 +264,18 @@ class MongooseMap extends Map {
|
|
|
263
264
|
}
|
|
264
265
|
|
|
265
266
|
/**
|
|
266
|
-
* Converts this map to a
|
|
267
|
-
*
|
|
267
|
+
* Converts this map to a POJO for `JSON.stringify()`. Set the `flattenMaps`
|
|
268
|
+
* option to `false` to convert this map to a native JavaScript Map instead.
|
|
268
269
|
*
|
|
269
270
|
* #### Example:
|
|
270
271
|
*
|
|
271
|
-
* doc.myMap.toJSON() instanceof Map; //
|
|
272
|
-
* doc.myMap.toJSON({ flattenMaps:
|
|
272
|
+
* doc.myMap.toJSON() instanceof Map; // false
|
|
273
|
+
* doc.myMap.toJSON({ flattenMaps: false }) instanceof Map; // true
|
|
273
274
|
*
|
|
274
275
|
* @api public
|
|
275
276
|
* @method toJSON
|
|
276
277
|
* @param {object} [options]
|
|
277
|
-
* @param {boolean} [options.flattenMaps=
|
|
278
|
+
* @param {boolean} [options.flattenMaps=true] set to `false` to convert the map to a native JavaScript Map rather than a POJO
|
|
278
279
|
* @memberOf Map
|
|
279
280
|
*/
|
|
280
281
|
|
package/lib/types/subdocument.js
CHANGED
|
@@ -177,8 +177,12 @@ Subdocument.prototype.markModified = function(path) {
|
|
|
177
177
|
return;
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
+
if (this.isNew) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
180
184
|
const myPath = this.$__pathRelativeToParent().replace(/\.$/, '');
|
|
181
|
-
if (parent.isDirectModified(myPath)
|
|
185
|
+
if (parent.isDirectModified(myPath)) {
|
|
182
186
|
return;
|
|
183
187
|
}
|
|
184
188
|
this.$__parent.markModified(fullPath, this);
|
package/lib/utils.js
CHANGED
|
@@ -14,6 +14,7 @@ const immediate = require('./helpers/immediate');
|
|
|
14
14
|
const isObject = require('./helpers/isObject');
|
|
15
15
|
const isMongooseArray = require('./types/array/isMongooseArray');
|
|
16
16
|
const isMongooseDocumentArray = require('./types/documentArray/isMongooseDocumentArray');
|
|
17
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
17
18
|
const isBsonType = require('./helpers/isBsonType');
|
|
18
19
|
const isPOJO = require('./helpers/isPOJO');
|
|
19
20
|
const getFunctionName = require('./helpers/getFunctionName');
|
|
@@ -154,13 +155,13 @@ exports.deepEqual = function deepEqual(a, b) {
|
|
|
154
155
|
return true;
|
|
155
156
|
}
|
|
156
157
|
|
|
157
|
-
if (a
|
|
158
|
+
if (isMongooseDocument(a)) {
|
|
158
159
|
a = a._doc;
|
|
159
160
|
} else if (isMongooseObject(a)) {
|
|
160
161
|
a = a.toObject();
|
|
161
162
|
}
|
|
162
163
|
|
|
163
|
-
if (b
|
|
164
|
+
if (isMongooseDocument(b)) {
|
|
164
165
|
b = b._doc;
|
|
165
166
|
} else if (isMongooseObject(b)) {
|
|
166
167
|
b = b.toObject();
|
|
@@ -251,7 +252,7 @@ exports.clonePOJOsAndArrays = function clonePOJOsAndArrays(val) {
|
|
|
251
252
|
return val;
|
|
252
253
|
}
|
|
253
254
|
// Skip documents because we assume they'll be cloned later. See gh-15312 for how documents are handled with `merge()`.
|
|
254
|
-
if (val
|
|
255
|
+
if (isMongooseDocument(val)) {
|
|
255
256
|
return val;
|
|
256
257
|
}
|
|
257
258
|
if (isPOJO(val)) {
|
|
@@ -929,7 +930,7 @@ exports.mergeClone = function(to, fromObj) {
|
|
|
929
930
|
// Skip inherited properties like `Object.prototype.toString` to avoid setting
|
|
930
931
|
// properties on shared objects. Document properties are getters on the
|
|
931
932
|
// prototype, so check `_doc`.
|
|
932
|
-
if (!Object.hasOwn(to
|
|
933
|
+
if (!Object.hasOwn(isMongooseDocument(to) ? to._doc : to, key) && key in to) {
|
|
933
934
|
continue;
|
|
934
935
|
}
|
|
935
936
|
if (typeof to[key] === 'undefined') {
|
|
@@ -947,7 +948,8 @@ exports.mergeClone = function(to, fromObj) {
|
|
|
947
948
|
}
|
|
948
949
|
if (exports.isObject(val)) {
|
|
949
950
|
let obj = val;
|
|
950
|
-
|
|
951
|
+
const isBuffer = Buffer.isBuffer(val) && val.isMongooseBuffer;
|
|
952
|
+
if (isMongooseObject(val) && !isBuffer) {
|
|
951
953
|
obj = obj.toObject({
|
|
952
954
|
transform: false,
|
|
953
955
|
virtuals: false,
|
|
@@ -956,7 +958,7 @@ exports.mergeClone = function(to, fromObj) {
|
|
|
956
958
|
flattenDecimals: false
|
|
957
959
|
});
|
|
958
960
|
}
|
|
959
|
-
if (
|
|
961
|
+
if (isBuffer) {
|
|
960
962
|
obj = Buffer.from(obj);
|
|
961
963
|
}
|
|
962
964
|
exports.mergeClone(to[key], obj);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mongoose",
|
|
3
3
|
"description": "Mongoose MongoDB ODM",
|
|
4
|
-
"version": "9.
|
|
4
|
+
"version": "9.13.0",
|
|
5
5
|
"author": "Guillermo Rauch <guillermo@learnboost.com>",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"mongodb",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@standard-schema/spec": "^1.1.0",
|
|
24
24
|
"kareem": "3.4.1",
|
|
25
|
-
"mongodb": "~7.
|
|
25
|
+
"mongodb": "~7.9",
|
|
26
26
|
"mpath": "0.9.0",
|
|
27
27
|
"mquery": "6.0.1",
|
|
28
28
|
"ms": "2.1.3",
|
package/types/models.d.ts
CHANGED
|
@@ -222,6 +222,14 @@ declare module 'mongoose' {
|
|
|
222
222
|
ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>['lean'] :
|
|
223
223
|
false;
|
|
224
224
|
|
|
225
|
+
/** True only if every member of the `defaultSort` union is set, so a union like `{ name: 1 } | undefined` is false */
|
|
226
|
+
type HasDefaultSortOption<TSchema> = ObtainSchemaGeneric<TSchema, 'TSchemaOptions'> extends { defaultSort: infer DefaultSort } ?
|
|
227
|
+
[Extract<DefaultSort, false | null | undefined | ''>] extends [never] ? true : false :
|
|
228
|
+
false;
|
|
229
|
+
|
|
230
|
+
/** `Model.findAndCount()` requires `sort` unless the schema sets `defaultSort`. */
|
|
231
|
+
type FindAndCountSortOption<TSchema> = HasDefaultSortOption<TSchema> extends true ? { sort?: any } : { sort: any };
|
|
232
|
+
|
|
225
233
|
/**
|
|
226
234
|
* Models are fancy constructors compiled from `Schema` definitions.
|
|
227
235
|
* An instance of a model is called a document.
|
|
@@ -968,22 +976,22 @@ declare module 'mongoose' {
|
|
|
968
976
|
findAndCount<const Projection extends ProjectionType<TRawDocType>>(
|
|
969
977
|
filter: QueryFilter<TRawDocType>,
|
|
970
978
|
projection: Projection,
|
|
971
|
-
options: QueryOptions<TRawDocType> &
|
|
979
|
+
options: QueryOptions<TRawDocType> & FindAndCountSortOption<TSchema> & { limit: number; lean: true } & mongodb.Abortable
|
|
972
980
|
): Promise<[ApplyProjection<TRawDocType, Projection>[], number]>;
|
|
973
981
|
findAndCount<ResultDoc = THydratedDocumentType>(
|
|
974
982
|
filter: QueryFilter<TRawDocType>,
|
|
975
983
|
projection: ProjectionType<TRawDocType> | null | undefined,
|
|
976
|
-
options: QueryOptions<TRawDocType> &
|
|
984
|
+
options: QueryOptions<TRawDocType> & FindAndCountSortOption<TSchema> & { limit: number; lean: true } & mongodb.Abortable
|
|
977
985
|
): Promise<[GetLeanResultType<TLeanResultType, TRawDocType[], 'find'>, number]>;
|
|
978
986
|
findAndCount<ResultDoc = THydratedDocumentType>(
|
|
979
987
|
filter: QueryFilter<TRawDocType>,
|
|
980
988
|
projection: ProjectionType<TRawDocType> | null | undefined,
|
|
981
|
-
options: QueryOptions<TRawDocType> &
|
|
989
|
+
options: QueryOptions<TRawDocType> & FindAndCountSortOption<TSchema> & { limit: number; lean: false } & mongodb.Abortable
|
|
982
990
|
): Promise<[ResultDoc[], number]>;
|
|
983
991
|
findAndCount<ResultDoc = THydratedDocumentType>(
|
|
984
992
|
filter: QueryFilter<TRawDocType>,
|
|
985
993
|
projection: ProjectionType<TRawDocType> | null | undefined,
|
|
986
|
-
options: QueryOptions<TRawDocType> &
|
|
994
|
+
options: QueryOptions<TRawDocType> & FindAndCountSortOption<TSchema> & { limit: number } & mongodb.Abortable
|
|
987
995
|
): Promise<[HasLeanOption<TSchema> extends true ? TLeanResultType[] : ResultDoc[], number]>;
|
|
988
996
|
|
|
989
997
|
/** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
|
package/types/query.d.ts
CHANGED
|
@@ -481,7 +481,7 @@ declare module 'mongoose' {
|
|
|
481
481
|
options?: QueryOptions<RawDocType> | null
|
|
482
482
|
): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TDocOverrides, TLeanResultType>;
|
|
483
483
|
|
|
484
|
-
/** Executes the query as a find and also runs countDocuments, returning [documents, count].
|
|
484
|
+
/** Executes the query as a find and also runs countDocuments, returning [documents, count]. Requires limit, and requires sort unless the schema has a `defaultSort`. */
|
|
485
485
|
findAndCount(): Promise<[ResultType, number]>;
|
|
486
486
|
|
|
487
487
|
/** Declares the query a findOne operation. When executed, returns the first found document. */
|
package/types/schemaoptions.d.ts
CHANGED
|
@@ -68,6 +68,13 @@ declare module 'mongoose' {
|
|
|
68
68
|
/** Default lean options for queries */
|
|
69
69
|
lean?: boolean | LeanOptions;
|
|
70
70
|
|
|
71
|
+
/**
|
|
72
|
+
* The sort to use for `find()`, `findOne()`, `findOneAndUpdate()`, `findOneAndReplace()`, `findOneAndDelete()`
|
|
73
|
+
* queries that don't specify a sort. Call `sort(null)` or `sort({})` to run an individual query with no sort.
|
|
74
|
+
* Does not apply to `updateOne()` and `replaceOne()` for compatibility with MongoDB < 8.0.
|
|
75
|
+
*/
|
|
76
|
+
defaultSort?: string | Record<string, SortOrder> | [string, SortOrder][] | Map<string, SortOrder> | false | null | undefined;
|
|
77
|
+
|
|
71
78
|
/** The timeseries option to use when creating the model's collection. */
|
|
72
79
|
timeseries?: mongodb.TimeSeriesCollectionOptions;
|
|
73
80
|
|