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/mongoose.js
CHANGED
|
@@ -28,6 +28,7 @@ const Aggregate = require('./aggregate');
|
|
|
28
28
|
const trusted = require('./helpers/query/trusted').trusted;
|
|
29
29
|
const sanitizeFilter = require('./helpers/query/sanitizeFilter');
|
|
30
30
|
const isBsonType = require('./helpers/isBsonType');
|
|
31
|
+
const getOwnProperty = require('./helpers/getOwnProperty');
|
|
31
32
|
const MongooseError = require('./error/mongooseError');
|
|
32
33
|
const SetOptionError = require('./error/setOptionError');
|
|
33
34
|
const applyEmbeddedDiscriminators = require('./helpers/discriminator/applyEmbeddedDiscriminators');
|
|
@@ -457,8 +458,8 @@ Mongoose.prototype.createConnection = function createConnection(uri, options) {
|
|
|
457
458
|
* @param {string} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
|
|
458
459
|
* @param {number} [options.maxPoolSize=100] The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](https://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
|
|
459
460
|
* @param {number} [options.minPoolSize=0] The minimum number of sockets the MongoDB driver will keep open for this connection.
|
|
460
|
-
* @param {number} [options.serverSelectionTimeoutMS]
|
|
461
|
-
* @param {number} [options.heartbeatFrequencyMS]
|
|
461
|
+
* @param {number} [options.serverSelectionTimeoutMS] The MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
|
|
462
|
+
* @param {number} [options.heartbeatFrequencyMS] The MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
|
|
462
463
|
* @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
|
|
463
464
|
* @param {number} [options.socketTimeoutMS=0] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. `socketTimeoutMS` defaults to 0, which means Node.js will not time out the socket due to inactivity. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
|
|
464
465
|
* @param {number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
|
|
@@ -604,7 +605,7 @@ Mongoose.prototype.model = function model(name, schema, collection, options) {
|
|
|
604
605
|
}
|
|
605
606
|
|
|
606
607
|
if (arguments.length === 1) {
|
|
607
|
-
const model = _mongoose.models
|
|
608
|
+
const model = getOwnProperty(_mongoose.models, name);
|
|
608
609
|
if (!model) {
|
|
609
610
|
throw new _mongoose.Error.MissingSchemaError(name);
|
|
610
611
|
}
|
|
@@ -676,6 +677,10 @@ Mongoose.prototype._model = function _model(name, schema, collection, options) {
|
|
|
676
677
|
throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
|
|
677
678
|
}
|
|
678
679
|
}
|
|
680
|
+
// Models are stored in POJOs keyed by name, so `__proto__` would change their prototype
|
|
681
|
+
if (name === '__proto__') {
|
|
682
|
+
throw new _mongoose.Error('Model name "__proto__" is not allowed');
|
|
683
|
+
}
|
|
679
684
|
|
|
680
685
|
if (schema) {
|
|
681
686
|
if (_mongoose.get('cloneSchemas')) {
|
|
@@ -1274,6 +1279,15 @@ Mongoose.prototype.CastError = MongooseError.CastError;
|
|
|
1274
1279
|
|
|
1275
1280
|
Mongoose.prototype.SchemaTypeOptions = require('./options/schemaTypeOptions');
|
|
1276
1281
|
|
|
1282
|
+
/**
|
|
1283
|
+
* The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
|
|
1284
|
+
*
|
|
1285
|
+
* @property mongo
|
|
1286
|
+
* @api public
|
|
1287
|
+
*/
|
|
1288
|
+
|
|
1289
|
+
Mongoose.prototype.mongo = null;
|
|
1290
|
+
|
|
1277
1291
|
/**
|
|
1278
1292
|
* The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
|
|
1279
1293
|
*
|
|
@@ -53,8 +53,13 @@ Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts);
|
|
|
53
53
|
Object.defineProperty(SchemaArrayOptions.prototype, 'of', opts);
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
* If set to `false`,
|
|
57
|
-
* If set to `true`,
|
|
56
|
+
* If set to `false`, Mongoose throws a `CastError` when you set a non-array value
|
|
57
|
+
* on this path. If set to `true`, Mongoose wraps the value in an array. Overrides
|
|
58
|
+
* the global `mongoose.Schema.Types.Array.options.castNonArrays` for this path.
|
|
59
|
+
* Values loaded from MongoDB are always wrapped, regardless of this option.
|
|
60
|
+
*
|
|
61
|
+
* This option only applies to the array it's set on, not to arrays nested
|
|
62
|
+
* inside it. For nested arrays, set `castNonArrays` on each level.
|
|
58
63
|
*
|
|
59
64
|
* #### Example:
|
|
60
65
|
*
|
|
@@ -62,6 +67,12 @@ Object.defineProperty(SchemaArrayOptions.prototype, 'of', opts);
|
|
|
62
67
|
* const doc = new Model({ x1: "some non-array value" });
|
|
63
68
|
* await doc.validate(); // Errors with "CastError"
|
|
64
69
|
*
|
|
70
|
+
* // Only the outer array: `1` is a CastError, but `[1, 2]` becomes `[[1, 2]]`
|
|
71
|
+
* new Schema({ matrix: { castNonArrays: false, type: [[Number]] } });
|
|
72
|
+
*
|
|
73
|
+
* // Both levels: `1` and `[1, 2]` are both CastErrors
|
|
74
|
+
* new Schema({ matrix: { castNonArrays: false, type: [{ type: [Number], castNonArrays: false }] } });
|
|
75
|
+
*
|
|
65
76
|
* @api public
|
|
66
77
|
* @property castNonArrays
|
|
67
78
|
* @memberOf SchemaArrayOptions
|
package/lib/query.js
CHANGED
|
@@ -27,8 +27,10 @@ const helpers = require('./queryHelpers');
|
|
|
27
27
|
const internalToObjectOptions = require('./options').internalToObjectOptions;
|
|
28
28
|
const isExclusive = require('./helpers/projection/isExclusive');
|
|
29
29
|
const isInclusive = require('./helpers/projection/isInclusive');
|
|
30
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
30
31
|
const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
|
|
31
32
|
const isSubpath = require('./helpers/projection/isSubpath');
|
|
33
|
+
const { logicalOperators } = require('./filters/operators');
|
|
32
34
|
const mpath = require('mpath');
|
|
33
35
|
const mquery = require('mquery');
|
|
34
36
|
const parseProjection = require('./helpers/projection/parseProjection');
|
|
@@ -70,6 +72,18 @@ const queryOptionMethods = new Set([
|
|
|
70
72
|
'wtimeout'
|
|
71
73
|
]);
|
|
72
74
|
|
|
75
|
+
// Operations that the schema-level `defaultSort` option applies to. These are the operations where
|
|
76
|
+
// sort determines the result. `deleteOne()` and `updateMany()` are excluded because the MongoDB driver
|
|
77
|
+
// silently ignores `sort` for those operations. `updateOne()` and `replaceOne()` are excluded because
|
|
78
|
+
// MongoDB < 8.0 throws an error if `sort` is set for those operations.
|
|
79
|
+
const defaultSortOps = new Set([
|
|
80
|
+
'find',
|
|
81
|
+
'findOne',
|
|
82
|
+
'findOneAndDelete',
|
|
83
|
+
'findOneAndReplace',
|
|
84
|
+
'findOneAndUpdate'
|
|
85
|
+
]);
|
|
86
|
+
|
|
73
87
|
// Map from operation name to the name of the function that executes the actual operation against MongoDB.
|
|
74
88
|
// Called a thunk for legacy reasons, "thunk" means function that takes exactly 1 param, a callback.
|
|
75
89
|
// Currently `_countDocuments()`, etc. are async functions that take no params.
|
|
@@ -1704,7 +1718,7 @@ Query.prototype.getOptions = function() {
|
|
|
1704
1718
|
*
|
|
1705
1719
|
* - [maxTimeMS](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/)
|
|
1706
1720
|
*
|
|
1707
|
-
* The following options are for `find()`, `findOne()`, `findOneAndUpdate()`, `findOneAndDelete()`, `updateOne()`, and `
|
|
1721
|
+
* The following options are for `find()`, `findOne()`, `findOneAndUpdate()`, `findOneAndDelete()`, `findOneAndReplace()`, `updateOne()`, and `replaceOne()`:
|
|
1708
1722
|
*
|
|
1709
1723
|
* - [sort](https://www.mongodb.com/docs/manual/reference/method/cursor.sort/)
|
|
1710
1724
|
*
|
|
@@ -2127,6 +2141,19 @@ Query.prototype._optionsForExec = function(model) {
|
|
|
2127
2141
|
if (!model) {
|
|
2128
2142
|
return options;
|
|
2129
2143
|
}
|
|
2144
|
+
if (utils.isEmptyObject(options.sort)) {
|
|
2145
|
+
// Empty sort means "no sort". The driver would send `sort: null` for `updateOne()` and
|
|
2146
|
+
// `replaceOne()`, which MongoDB < 8.0 rejects.
|
|
2147
|
+
delete options.sort;
|
|
2148
|
+
} else if (options.sort == null && !options.tailable && defaultSortOps.has(this.op)) {
|
|
2149
|
+
// Apply `defaultSort` to the options we send to MongoDB rather than to `this.options`, so an
|
|
2150
|
+
// explicit `sort()` on a clone of this query replaces the default instead of merging with it.
|
|
2151
|
+
// Tailable cursors can't sort, and `$near` queries already sort by distance.
|
|
2152
|
+
const defaultSort = this.schema?.options.defaultSort;
|
|
2153
|
+
if (defaultSort && !_hasNearCondition(this._conditions)) {
|
|
2154
|
+
options.sort = _addSortKeys({}, defaultSort);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2130
2157
|
applyReadConcern(model.schema, options);
|
|
2131
2158
|
// Apply schema-level `writeConcern` option
|
|
2132
2159
|
applyWriteConcern(model.schema, options);
|
|
@@ -2538,6 +2565,8 @@ Query.prototype.find = function(conditions) {
|
|
|
2538
2565
|
* Executes the query as a `find()` and also runs a `countDocuments()` query
|
|
2539
2566
|
* on the same filter, returning `[documents, count]`. The count ignores
|
|
2540
2567
|
* `skip` and `limit` so that it returns the total number of matching documents.
|
|
2568
|
+
* Requires `limit`, and requires `sort` unless the schema has a [`defaultSort`](https://mongoosejs.com/docs/guide.html#defaultSort).
|
|
2569
|
+
* Throws if `sort` is empty, like `sort(null)`.
|
|
2541
2570
|
*
|
|
2542
2571
|
* #### Example:
|
|
2543
2572
|
*
|
|
@@ -2549,9 +2578,13 @@ Query.prototype.find = function(conditions) {
|
|
|
2549
2578
|
*/
|
|
2550
2579
|
|
|
2551
2580
|
Query.prototype.findAndCount = async function findAndCount() {
|
|
2552
|
-
if (this.options.sort == null) {
|
|
2581
|
+
if (this.options.sort == null && !this.schema?.options.defaultSort) {
|
|
2553
2582
|
throw new MongooseError('Query.prototype.findAndCount() requires sort. Use `sort()` to set a sort order before calling `findAndCount()`.');
|
|
2554
2583
|
}
|
|
2584
|
+
// `sort(null)`, `sort(undefined)`, and `sort({})` all mean "no sort", which would make pagination unstable
|
|
2585
|
+
if (utils.isEmptyObject(this.options.sort)) {
|
|
2586
|
+
throw new MongooseError('Query.prototype.findAndCount() does not allow an empty sort, like `sort(null)`. Remove the `sort()` call to use the schema\'s `defaultSort`.');
|
|
2587
|
+
}
|
|
2555
2588
|
if (this.options.limit == null) {
|
|
2556
2589
|
throw new MongooseError('Query.prototype.findAndCount() requires limit. Use `limit()` to set a limit before calling `findAndCount()`.');
|
|
2557
2590
|
}
|
|
@@ -2627,7 +2660,7 @@ Query.prototype.merge = function(source) {
|
|
|
2627
2660
|
utils.merge(this._conditions, { _id: source }, opts);
|
|
2628
2661
|
|
|
2629
2662
|
return this;
|
|
2630
|
-
} else if (source
|
|
2663
|
+
} else if (isMongooseDocument(source)) {
|
|
2631
2664
|
source = source.toObject(internalToObjectOptions);
|
|
2632
2665
|
}
|
|
2633
2666
|
|
|
@@ -3120,6 +3153,9 @@ Query.prototype.distinct = function(field, conditions, options) {
|
|
|
3120
3153
|
* // also possible is to use a array with array key-value pairs
|
|
3121
3154
|
* query.sort([['field', 'asc']]);
|
|
3122
3155
|
*
|
|
3156
|
+
* // run this query with no sort, ignoring the schema's `defaultSort`
|
|
3157
|
+
* query.sort(null);
|
|
3158
|
+
*
|
|
3123
3159
|
* #### Note:
|
|
3124
3160
|
*
|
|
3125
3161
|
* Cannot be used with `distinct()`
|
|
@@ -3146,7 +3182,37 @@ Query.prototype.sort = function(arg, options) {
|
|
|
3146
3182
|
if (options?.override) {
|
|
3147
3183
|
this.options.sort = {};
|
|
3148
3184
|
}
|
|
3149
|
-
|
|
3185
|
+
_addSortKeys(this.options.sort, arg);
|
|
3186
|
+
|
|
3187
|
+
return this;
|
|
3188
|
+
};
|
|
3189
|
+
|
|
3190
|
+
/*!
|
|
3191
|
+
* Returns true if `filter` has a `$near` or `$nearSphere` condition, including within logical operators.
|
|
3192
|
+
*/
|
|
3193
|
+
|
|
3194
|
+
function _hasNearCondition(filter) {
|
|
3195
|
+
for (const key of Object.keys(filter)) {
|
|
3196
|
+
const val = filter[key];
|
|
3197
|
+
if (val == null || typeof val !== 'object') {
|
|
3198
|
+
continue;
|
|
3199
|
+
}
|
|
3200
|
+
if (logicalOperators.has(key)) {
|
|
3201
|
+
if (Array.isArray(val) && val.some(clause => clause != null && typeof clause === 'object' && _hasNearCondition(clause))) {
|
|
3202
|
+
return true;
|
|
3203
|
+
}
|
|
3204
|
+
} else if (Object.hasOwn(val, '$near') || Object.hasOwn(val, '$nearSphere')) {
|
|
3205
|
+
return true;
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
return false;
|
|
3209
|
+
}
|
|
3210
|
+
|
|
3211
|
+
/*!
|
|
3212
|
+
* Add the keys from `arg`, which can be any value that `Query.prototype.sort()` accepts, to the `sort` object.
|
|
3213
|
+
*/
|
|
3214
|
+
|
|
3215
|
+
function _addSortKeys(sort, arg) {
|
|
3150
3216
|
if (typeof arg === 'string') {
|
|
3151
3217
|
const properties = arg.indexOf(' ') === -1 ? [arg] : arg.split(' ');
|
|
3152
3218
|
for (let property of properties) {
|
|
@@ -3189,8 +3255,8 @@ Query.prototype.sort = function(arg, options) {
|
|
|
3189
3255
|
throw new TypeError('Invalid sort() argument. Must be a string, object, array, or map.');
|
|
3190
3256
|
}
|
|
3191
3257
|
|
|
3192
|
-
return
|
|
3193
|
-
}
|
|
3258
|
+
return sort;
|
|
3259
|
+
}
|
|
3194
3260
|
|
|
3195
3261
|
/*!
|
|
3196
3262
|
* Convert sort values
|
|
@@ -3203,7 +3269,8 @@ function _handleSortValue(val, key) {
|
|
|
3203
3269
|
if (val === -1 || val === 'desc' || val === 'descending') {
|
|
3204
3270
|
return -1;
|
|
3205
3271
|
}
|
|
3206
|
-
|
|
3272
|
+
// Only own `$meta`, because the MongoDB driver only reads own properties
|
|
3273
|
+
if (val != null && Object.hasOwn(val, '$meta') && val.$meta != null) {
|
|
3207
3274
|
return { $meta: val.$meta };
|
|
3208
3275
|
}
|
|
3209
3276
|
throw new TypeError('Invalid sort value: { ' + key + ': ' + val + ' }');
|
package/lib/schema/array.js
CHANGED
|
@@ -24,6 +24,7 @@ const castToNumber = require('./operators/helpers').castToNumber;
|
|
|
24
24
|
const geospatial = require('./operators/geospatial');
|
|
25
25
|
const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
|
|
26
26
|
const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue');
|
|
27
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
27
28
|
|
|
28
29
|
let MongooseArray;
|
|
29
30
|
let EmbeddedDoc;
|
|
@@ -295,25 +296,28 @@ SchemaArray.prototype.applyGetters = function(value, scope) {
|
|
|
295
296
|
};
|
|
296
297
|
|
|
297
298
|
SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) {
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
//
|
|
301
|
-
|
|
299
|
+
// No need to wrap empty arrays
|
|
300
|
+
if (this.embeddedSchemaType.$isMongooseArray && value != null && value.length !== 0) {
|
|
301
|
+
// This array and its nested arrays, outermost first
|
|
302
|
+
const levels = [];
|
|
302
303
|
let arr = this;
|
|
303
304
|
while (arr != null &&
|
|
304
305
|
arr.$isMongooseArray &&
|
|
305
306
|
!arr.$isMongooseDocumentArray) {
|
|
306
|
-
|
|
307
|
+
levels.push(arr);
|
|
307
308
|
arr = arr.embeddedSchemaType;
|
|
308
309
|
}
|
|
309
310
|
|
|
310
|
-
//
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
311
|
+
// Check nesting levels and wrap in array if necessary. A value nested
|
|
312
|
+
// `valueDepth.max` levels deep puts non-array values in every level from
|
|
313
|
+
// `valueDepth.max` inward, so each of those levels must allow wrapping.
|
|
314
|
+
const valueDepth = arrayDepth(value);
|
|
315
|
+
if (valueDepth.min === valueDepth.max &&
|
|
316
|
+
valueDepth.max < levels.length &&
|
|
317
|
+
valueDepth.containsNonArrayItem &&
|
|
318
|
+
levels.slice(valueDepth.max).every(level => level.options.castNonArrays ?? SchemaArray.options.castNonArrays)) {
|
|
319
|
+
for (let i = valueDepth.max; i < levels.length; ++i) {
|
|
320
|
+
value = [value];
|
|
317
321
|
}
|
|
318
322
|
}
|
|
319
323
|
}
|
|
@@ -548,7 +552,7 @@ SchemaArray.prototype.castForQuery = function($conditional, val, context) {
|
|
|
548
552
|
let handler;
|
|
549
553
|
|
|
550
554
|
if ($conditional != null) {
|
|
551
|
-
handler = this.$conditionalHandlers
|
|
555
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
552
556
|
|
|
553
557
|
if (!handler) {
|
|
554
558
|
throw new Error('Can\'t use ' + $conditional + ' with Array.');
|
package/lib/schema/bigint.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
const CastError = require('../error/cast');
|
|
8
8
|
const SchemaType = require('../schemaType');
|
|
9
9
|
const castBigInt = require('../cast/bigint');
|
|
10
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* BigInt SchemaType constructor.
|
|
@@ -220,7 +221,7 @@ function handleSingle(val, context) {
|
|
|
220
221
|
SchemaBigInt.prototype.castForQuery = function($conditional, val, context) {
|
|
221
222
|
let handler;
|
|
222
223
|
if ($conditional != null) {
|
|
223
|
-
handler = this.$conditionalHandlers
|
|
224
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
224
225
|
|
|
225
226
|
if (handler) {
|
|
226
227
|
return handler.call(this, val);
|
package/lib/schema/boolean.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
const CastError = require('../error/cast');
|
|
8
8
|
const SchemaType = require('../schemaType');
|
|
9
9
|
const castBoolean = require('../cast/boolean');
|
|
10
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Boolean SchemaType constructor.
|
|
@@ -264,7 +265,7 @@ Object.defineProperty(SchemaBoolean.prototype, '$conditionalHandlers', {
|
|
|
264
265
|
SchemaBoolean.prototype.castForQuery = function($conditional, val, context) {
|
|
265
266
|
let handler;
|
|
266
267
|
if ($conditional != null) {
|
|
267
|
-
handler = this.$conditionalHandlers
|
|
268
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
268
269
|
|
|
269
270
|
if (handler) {
|
|
270
271
|
return handler.call(this, val);
|
package/lib/schema/buffer.js
CHANGED
|
@@ -9,6 +9,7 @@ const SchemaBufferOptions = require('../options/schemaBufferOptions');
|
|
|
9
9
|
const SchemaType = require('../schemaType');
|
|
10
10
|
const handleBitwiseOperator = require('./operators/bitwise');
|
|
11
11
|
const utils = require('../utils');
|
|
12
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
12
13
|
|
|
13
14
|
const Binary = MongooseBuffer.Binary;
|
|
14
15
|
const CastError = SchemaType.CastError;
|
|
@@ -145,16 +146,14 @@ SchemaBuffer.prototype.checkRequired = function(value, doc) {
|
|
|
145
146
|
SchemaBuffer.prototype.cast = function(value, doc, init, prev, options) {
|
|
146
147
|
let ret;
|
|
147
148
|
if (SchemaType._isRef(this, value, doc, init)) {
|
|
148
|
-
if (value
|
|
149
|
+
if (Buffer.isBuffer(value) && value.isMongooseBuffer) {
|
|
149
150
|
return value;
|
|
150
151
|
}
|
|
151
152
|
|
|
152
153
|
if (Buffer.isBuffer(value)) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
value._subtype = this.options.subtype;
|
|
157
|
-
}
|
|
154
|
+
value = new MongooseBuffer(value, [this.path, doc]);
|
|
155
|
+
if (this.options.subtype != null) {
|
|
156
|
+
value._subtype = this.options.subtype;
|
|
158
157
|
}
|
|
159
158
|
return value;
|
|
160
159
|
}
|
|
@@ -178,16 +177,14 @@ SchemaBuffer.prototype.cast = function(value, doc, init, prev, options) {
|
|
|
178
177
|
value = value._id;
|
|
179
178
|
}
|
|
180
179
|
|
|
181
|
-
if (value
|
|
180
|
+
if (Buffer.isBuffer(value) && value.isMongooseBuffer) {
|
|
182
181
|
return value;
|
|
183
182
|
}
|
|
184
183
|
|
|
185
184
|
if (Buffer.isBuffer(value)) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
value._subtype = this.options.subtype;
|
|
190
|
-
}
|
|
185
|
+
value = new MongooseBuffer(value, [this.path, doc]);
|
|
186
|
+
if (this.options.subtype != null) {
|
|
187
|
+
value._subtype = this.options.subtype;
|
|
191
188
|
}
|
|
192
189
|
return value;
|
|
193
190
|
}
|
|
@@ -299,7 +296,7 @@ Object.defineProperty(SchemaBuffer.prototype, '$conditionalHandlers', {
|
|
|
299
296
|
SchemaBuffer.prototype.castForQuery = function($conditional, val, context) {
|
|
300
297
|
let handler;
|
|
301
298
|
if ($conditional != null) {
|
|
302
|
-
handler = this.$conditionalHandlers
|
|
299
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
303
300
|
if (!handler) {
|
|
304
301
|
throw new Error('Can\'t use ' + $conditional + ' with Buffer.');
|
|
305
302
|
}
|
package/lib/schema/date.js
CHANGED
|
@@ -10,6 +10,7 @@ const SchemaType = require('../schemaType');
|
|
|
10
10
|
const castDate = require('../cast/date');
|
|
11
11
|
const getConstructorName = require('../helpers/getConstructorName');
|
|
12
12
|
const utils = require('../utils');
|
|
13
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
13
14
|
|
|
14
15
|
const CastError = SchemaType.CastError;
|
|
15
16
|
|
|
@@ -435,7 +436,7 @@ SchemaDate.prototype.castForQuery = function($conditional, val, context) {
|
|
|
435
436
|
}
|
|
436
437
|
}
|
|
437
438
|
|
|
438
|
-
const handler = this.$conditionalHandlers
|
|
439
|
+
const handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
439
440
|
|
|
440
441
|
if (!handler) {
|
|
441
442
|
throw new Error('Can\'t use ' + $conditional + ' with Date.');
|
|
@@ -505,15 +505,12 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
|
|
|
505
505
|
}
|
|
506
506
|
rawArray[i] = subdoc.$init(rawArray[i], options);
|
|
507
507
|
} else {
|
|
508
|
-
if
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
subdoc.set(rawArray[i]);
|
|
515
|
-
// if set() is hooked it will have no return value
|
|
516
|
-
// see gh-746
|
|
508
|
+
// Reuse the existing subdoc at the same index if it has the same `_id` and data, so
|
|
509
|
+
// references to it stay valid. Only checking the same index keeps this O(n) (gh-16673).
|
|
510
|
+
subdoc = prev?.[i];
|
|
511
|
+
if (subdoc?._doc != null && rawArray[i]._id != null &&
|
|
512
|
+
utils.deepEqual(rawArray[i]._id, subdoc._doc._id) &&
|
|
513
|
+
utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
|
|
517
514
|
rawArray[i] = subdoc;
|
|
518
515
|
} else {
|
|
519
516
|
try {
|
|
@@ -531,6 +528,16 @@ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
|
|
|
531
528
|
}
|
|
532
529
|
}
|
|
533
530
|
|
|
531
|
+
// A subdoc can only belong to one array, so subdocs reused from `prev` move to the new array,
|
|
532
|
+
// like gh-5189. Only do this after casting succeeded, so a CastError leaves `prev` consistent.
|
|
533
|
+
if (utils.isMongooseDocumentArray(prev)) {
|
|
534
|
+
for (let i = 0; i < len; ++i) {
|
|
535
|
+
if (rawArray[i] != null && rawArray[i] === prev[i]) {
|
|
536
|
+
rawArray[i].__parentArray = value;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
534
541
|
return value;
|
|
535
542
|
};
|
|
536
543
|
|
package/lib/schema/int32.js
CHANGED
|
@@ -8,6 +8,7 @@ const CastError = require('../error/cast');
|
|
|
8
8
|
const SchemaType = require('../schemaType');
|
|
9
9
|
const castInt32 = require('../cast/int32');
|
|
10
10
|
const handleBitwiseOperator = require('./operators/bitwise');
|
|
11
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Int32 SchemaType constructor.
|
|
@@ -244,7 +245,7 @@ function handleSingle(val, context) {
|
|
|
244
245
|
SchemaInt32.prototype.castForQuery = function($conditional, val, context) {
|
|
245
246
|
let handler;
|
|
246
247
|
if ($conditional != null) {
|
|
247
|
-
handler = this.$conditionalHandlers
|
|
248
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
248
249
|
|
|
249
250
|
if (handler) {
|
|
250
251
|
return handler.call(this, val);
|
package/lib/schema/number.js
CHANGED
|
@@ -10,6 +10,7 @@ const SchemaType = require('../schemaType');
|
|
|
10
10
|
const castNumber = require('../cast/number');
|
|
11
11
|
const handleBitwiseOperator = require('./operators/bitwise');
|
|
12
12
|
const utils = require('../utils');
|
|
13
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
13
14
|
|
|
14
15
|
const CastError = SchemaType.CastError;
|
|
15
16
|
|
|
@@ -476,7 +477,7 @@ Object.defineProperty(SchemaNumber.prototype, '$conditionalHandlers', {
|
|
|
476
477
|
SchemaNumber.prototype.castForQuery = function($conditional, val, context) {
|
|
477
478
|
let handler;
|
|
478
479
|
if ($conditional != null) {
|
|
479
|
-
handler = this.$conditionalHandlers
|
|
480
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
480
481
|
if (!handler) {
|
|
481
482
|
throw new MongooseError('Can\'t use ' + $conditional + ' with Number.');
|
|
482
483
|
}
|
package/lib/schema/string.js
CHANGED
|
@@ -10,6 +10,7 @@ const SchemaStringOptions = require('../options/schemaStringOptions');
|
|
|
10
10
|
const castString = require('../cast/string');
|
|
11
11
|
const utils = require('../utils');
|
|
12
12
|
const isBsonType = require('../helpers/isBsonType');
|
|
13
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
13
14
|
|
|
14
15
|
const CastError = SchemaType.CastError;
|
|
15
16
|
|
|
@@ -693,7 +694,7 @@ Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', {
|
|
|
693
694
|
SchemaString.prototype.castForQuery = function($conditional, val, context) {
|
|
694
695
|
let handler;
|
|
695
696
|
if ($conditional != null) {
|
|
696
|
-
handler = this.$conditionalHandlers
|
|
697
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
697
698
|
if (!handler) {
|
|
698
699
|
throw new Error('Can\'t use ' + $conditional + ' with String.');
|
|
699
700
|
}
|
|
@@ -21,6 +21,7 @@ const internalToObjectOptions = require('../options').internalToObjectOptions;
|
|
|
21
21
|
const isExclusive = require('../helpers/projection/isExclusive');
|
|
22
22
|
const utils = require('../utils');
|
|
23
23
|
const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
|
|
24
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
24
25
|
|
|
25
26
|
let SubdocumentType;
|
|
26
27
|
|
|
@@ -237,7 +238,7 @@ SchemaSubdocument.prototype.cast = function(val, doc, init, priorVal, options) {
|
|
|
237
238
|
SchemaSubdocument.prototype.castForQuery = function($conditional, val, context, options) {
|
|
238
239
|
let handler;
|
|
239
240
|
if ($conditional != null) {
|
|
240
|
-
handler = this.$conditionalHandlers
|
|
241
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
241
242
|
if (!handler) {
|
|
242
243
|
throw new Error('Can\'t use ' + $conditional);
|
|
243
244
|
}
|
package/lib/schema/uuid.js
CHANGED
|
@@ -9,6 +9,7 @@ const CastError = SchemaType.CastError;
|
|
|
9
9
|
const castUUID = require('../cast/uuid');
|
|
10
10
|
const utils = require('../utils');
|
|
11
11
|
const handleBitwiseOperator = require('./operators/bitwise');
|
|
12
|
+
const getConditionalHandler = require('../helpers/schematype/getConditionalHandler');
|
|
12
13
|
|
|
13
14
|
const UUID_FORMAT = castUUID.UUID_FORMAT;
|
|
14
15
|
|
|
@@ -264,7 +265,7 @@ Object.defineProperty(SchemaUUID.prototype, '$conditionalHandlers', {
|
|
|
264
265
|
SchemaUUID.prototype.castForQuery = function($conditional, val, context) {
|
|
265
266
|
let handler;
|
|
266
267
|
if ($conditional != null) {
|
|
267
|
-
handler = this.$conditionalHandlers
|
|
268
|
+
handler = getConditionalHandler(this.$conditionalHandlers, $conditional);
|
|
268
269
|
if (!handler)
|
|
269
270
|
throw new Error('Can\'t use ' + $conditional + ' with UUID.');
|
|
270
271
|
return handler.call(this, val, context);
|