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.
- 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 +5 -4
- package/lib/index.js +7 -0
- package/lib/internal.js +4 -0
- package/lib/model.js +28 -14
- package/lib/mongoose.js +17 -3
- package/lib/options/schemaArrayOptions.js +13 -2
- package/lib/query.js +74 -7
- package/lib/schema/array.js +17 -13
- 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 +88 -41
- 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/pipelinestage.d.ts +4 -2
- package/types/query.d.ts +1 -1
- package/types/schemaoptions.d.ts +7 -0
- package/types/utility.d.ts +117 -5
- package/tstyche.json +0 -7
- package/tstyche.matrix.json +0 -9
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
|
|
|
@@ -1745,7 +1750,9 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
|
|
|
1745
1750
|
? cast[options.typeKey]
|
|
1746
1751
|
: cast;
|
|
1747
1752
|
if (Array.isArray(type)) {
|
|
1748
|
-
|
|
1753
|
+
// Pass `cast` rather than `type` so options on a nested array, like
|
|
1754
|
+
// `[{ type: [Number], castNonArrays: false }]`, aren't dropped.
|
|
1755
|
+
return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj, null, this);
|
|
1749
1756
|
}
|
|
1750
1757
|
|
|
1751
1758
|
name = typeof type === 'string'
|
|
@@ -1929,47 +1936,21 @@ Schema.prototype.pathsWithTransforms = function pathsWithTransforms(invalidate)
|
|
|
1929
1936
|
};
|
|
1930
1937
|
|
|
1931
1938
|
/**
|
|
1932
|
-
* Returns the paths in this schema that have a default,
|
|
1933
|
-
*
|
|
1934
|
-
*
|
|
1935
|
-
*
|
|
1939
|
+
* Returns a `SchemaDefaultsCache` with the paths in this schema that have a default,
|
|
1940
|
+
* both for the whole schema and grouped by nested path. This lets `applyDefaults()`
|
|
1941
|
+
* and setting nested paths skip iterating over every path in the schema for every
|
|
1942
|
+
* document. Computed when the first document is created, and cleared when
|
|
1936
1943
|
* compiling or recompiling a model that uses this schema or if paths are added or removed.
|
|
1937
1944
|
*
|
|
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
1945
|
* @api private
|
|
1948
|
-
* @return {
|
|
1946
|
+
* @return {SchemaDefaultsCache}
|
|
1949
1947
|
*/
|
|
1950
1948
|
|
|
1951
|
-
Schema.prototype.
|
|
1952
|
-
if (this.
|
|
1953
|
-
|
|
1949
|
+
Schema.prototype._getDefaultsCache = function _getDefaultsCache() {
|
|
1950
|
+
if (this._defaultsCache == null) {
|
|
1951
|
+
this._defaultsCache = new SchemaDefaultsCache(this);
|
|
1954
1952
|
}
|
|
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);
|
|
1969
|
-
}
|
|
1970
|
-
|
|
1971
|
-
this._pathsWithDefaults = { paths, schemaTypes };
|
|
1972
|
-
return this._pathsWithDefaults;
|
|
1953
|
+
return this._defaultsCache;
|
|
1973
1954
|
};
|
|
1974
1955
|
|
|
1975
1956
|
/**
|
|
@@ -2742,13 +2723,13 @@ Schema.prototype.virtual = function(name, options) {
|
|
|
2742
2723
|
if (opts?.hydratedPopulatedDocs && !options.count) {
|
|
2743
2724
|
const modelNames = virtual._getModelNamesForPopulate(this);
|
|
2744
2725
|
const populatedVal = this.$$populatedVirtuals[name];
|
|
2745
|
-
if (!Array.isArray(populatedVal) && !populatedVal
|
|
2726
|
+
if (!Array.isArray(populatedVal) && !isMongooseDocument(populatedVal) && modelNames?.length === 1) {
|
|
2746
2727
|
const PopulateModel = this.db.model(modelNames[0]);
|
|
2747
2728
|
this.$$populatedVirtuals[name] = PopulateModel.hydrate(populatedVal);
|
|
2748
2729
|
} else if (Array.isArray(populatedVal) && modelNames?.length === 1) {
|
|
2749
2730
|
const PopulateModel = this.db.model(modelNames[0]);
|
|
2750
2731
|
for (let i = 0; i < populatedVal.length; ++i) {
|
|
2751
|
-
if (!populatedVal[i]
|
|
2732
|
+
if (!isMongooseDocument(populatedVal[i])) {
|
|
2752
2733
|
populatedVal[i] = PopulateModel.hydrate(populatedVal[i], null, { hydratedPopulatedDocs: true });
|
|
2753
2734
|
}
|
|
2754
2735
|
}
|
|
@@ -2874,8 +2855,19 @@ Schema.prototype.remove = function(path) {
|
|
|
2874
2855
|
if (this.path(name) == null && !this.nested[name]) {
|
|
2875
2856
|
return;
|
|
2876
2857
|
}
|
|
2877
|
-
this.
|
|
2858
|
+
this._defaultsCache = null;
|
|
2878
2859
|
this._hasSelectedPaths = undefined;
|
|
2860
|
+
// Drop aliases that point to the removed path, or to a path under it, along
|
|
2861
|
+
// with their virtuals, so they don't keep translating keys to a missing path.
|
|
2862
|
+
for (const [alias, target] of Object.entries(this.aliases)) {
|
|
2863
|
+
if (target === name || target.startsWith(name + '.')) {
|
|
2864
|
+
delete this.aliases[alias];
|
|
2865
|
+
delete this.virtuals[alias];
|
|
2866
|
+
if (get(this.tree, alias) instanceof VirtualType) {
|
|
2867
|
+
_deletePath(this, alias);
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2879
2871
|
if (this.nested[name]) {
|
|
2880
2872
|
const allKeys = Object.keys(this.paths).
|
|
2881
2873
|
concat(Object.keys(this.nested));
|
|
@@ -2976,6 +2968,22 @@ Schema.prototype.removeVirtual = function(path) {
|
|
|
2976
2968
|
}
|
|
2977
2969
|
|
|
2978
2970
|
for (const virtual of path) {
|
|
2971
|
+
if (Object.hasOwn(this.aliases, virtual)) {
|
|
2972
|
+
// `pick()` rebuilds aliases from the SchemaType's options, and `omit()` and
|
|
2973
|
+
// `add(schema)` rebuild them from the tree, so drop the alias from both or it
|
|
2974
|
+
// comes back on every schema derived from this one.
|
|
2975
|
+
const aliasedPath = this.aliases[virtual];
|
|
2976
|
+
delete this.aliases[virtual];
|
|
2977
|
+
const treeEntry = get(this.tree, aliasedPath);
|
|
2978
|
+
const treeOptions = treeEntry instanceof SchemaType ? treeEntry.options : treeEntry;
|
|
2979
|
+
for (const options of [this.paths[aliasedPath]?.options, treeOptions]) {
|
|
2980
|
+
if (options?.alias === virtual) {
|
|
2981
|
+
delete options.alias;
|
|
2982
|
+
} else if (Array.isArray(options?.alias)) {
|
|
2983
|
+
options.alias = options.alias.filter(a => a !== virtual);
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2979
2987
|
delete this.paths[virtual];
|
|
2980
2988
|
delete this.virtuals[virtual];
|
|
2981
2989
|
if (virtual.indexOf('.') !== -1) {
|
|
@@ -3299,12 +3307,51 @@ function isArrayFilter(piece) {
|
|
|
3299
3307
|
*/
|
|
3300
3308
|
|
|
3301
3309
|
Schema.prototype._preCompile = function _preCompile() {
|
|
3310
|
+
// Check `defaultSort` again in case it was changed after the schema was created
|
|
3311
|
+
_validateDefaultSort(this.options.defaultSort);
|
|
3302
3312
|
this.plugin(idGetter, { deduplicate: true });
|
|
3303
3313
|
_precomputeOptimisticConcurrency(this);
|
|
3304
3314
|
_clearDerivedPathCaches(this, new Set());
|
|
3305
3315
|
this._hasSelectedPaths = _hasSelectedPaths(this, []);
|
|
3306
3316
|
};
|
|
3307
3317
|
|
|
3318
|
+
/*!
|
|
3319
|
+
* Throws if `defaultSort` is not a valid value for the `defaultSort` schema option. Disallows `$meta` sorts,
|
|
3320
|
+
* like `{ score: { $meta: 'textScore' } }`, because MongoDB throws on `$meta` sorts for queries without `$text`.
|
|
3321
|
+
*/
|
|
3322
|
+
|
|
3323
|
+
function _validateDefaultSort(defaultSort) {
|
|
3324
|
+
if (!defaultSort) {
|
|
3325
|
+
return;
|
|
3326
|
+
}
|
|
3327
|
+
// An empty `defaultSort` would silently mean "no sort", which would let `findAndCount()` run unsorted.
|
|
3328
|
+
// Use `defaultSort: null` to disable the default sort instead.
|
|
3329
|
+
const emptyError = '`defaultSort` must not be empty, use `defaultSort: null` to disable the default sort';
|
|
3330
|
+
if (typeof defaultSort === 'string') {
|
|
3331
|
+
if (defaultSort.trim() === '') {
|
|
3332
|
+
throw new MongooseError(emptyError);
|
|
3333
|
+
}
|
|
3334
|
+
return;
|
|
3335
|
+
}
|
|
3336
|
+
if (typeof defaultSort !== 'object') {
|
|
3337
|
+
throw new MongooseError('`defaultSort` must be falsy, string, object, array, or Map, got `' + (typeof defaultSort) + '`');
|
|
3338
|
+
}
|
|
3339
|
+
const entries = defaultSort instanceof Map ?
|
|
3340
|
+
Array.from(defaultSort) :
|
|
3341
|
+
Array.isArray(defaultSort) ? defaultSort : Object.entries(defaultSort);
|
|
3342
|
+
if (entries.length === 0) {
|
|
3343
|
+
throw new MongooseError(emptyError);
|
|
3344
|
+
}
|
|
3345
|
+
for (const entry of entries) {
|
|
3346
|
+
if (!Array.isArray(entry)) {
|
|
3347
|
+
throw new MongooseError('`defaultSort` array must be an array of [key, value] arrays, like `[[\'name\', 1]]`');
|
|
3348
|
+
}
|
|
3349
|
+
if (entry[1] != null && Object.hasOwn(entry[1], '$meta')) {
|
|
3350
|
+
throw new MongooseError('`defaultSort` does not support `$meta` sorts, got `$meta` for `' + entry[0] + '`');
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
|
|
3308
3355
|
/*!
|
|
3309
3356
|
* Clears caches that are derived from `schema.paths` on `schema` and all of its
|
|
3310
3357
|
* nested schemas, because nested schemas can change until the model is compiled.
|
|
@@ -3316,7 +3363,7 @@ function _clearDerivedPathCaches(schema, seen) {
|
|
|
3316
3363
|
}
|
|
3317
3364
|
seen.add(schema);
|
|
3318
3365
|
|
|
3319
|
-
schema.
|
|
3366
|
+
schema._defaultsCache = null;
|
|
3320
3367
|
schema._pathsWithTransforms = undefined;
|
|
3321
3368
|
for (const { schema: childSchema } of schema.childSchemas) {
|
|
3322
3369
|
_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.1",
|
|
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/pipelinestage.d.ts
CHANGED
|
@@ -323,11 +323,13 @@ declare module 'mongoose' {
|
|
|
323
323
|
exact?: boolean;
|
|
324
324
|
index: string,
|
|
325
325
|
path: string,
|
|
326
|
-
queryVector: number[],
|
|
327
326
|
numCandidates?: number,
|
|
328
327
|
limit: number,
|
|
329
328
|
filter?: Expression,
|
|
330
|
-
}
|
|
329
|
+
} & (
|
|
330
|
+
{ queryVector: number[], query?: never, model?: never } |
|
|
331
|
+
{ query: { text: string }, queryVector?: never, model?: string }
|
|
332
|
+
)
|
|
331
333
|
}
|
|
332
334
|
|
|
333
335
|
}
|
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
|
|