mongoose 9.12.2 → 9.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/aggregate.js +4 -0
- package/lib/cast.js +4 -2
- package/lib/connection.js +11 -8
- package/lib/defaults/schemaDefaultsCache.js +62 -0
- package/lib/document.js +69 -53
- 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/cast$expr.js +16 -0
- 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 +16 -2
- package/lib/index.js +7 -0
- package/lib/internal.js +4 -0
- package/lib/model.js +28 -12
- 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 +18 -10
- 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 +3 -3
- package/types/expressions.d.ts +1 -1
- package/types/index.d.ts +3 -0
- 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/aggregate.js
CHANGED
|
@@ -246,6 +246,10 @@ Aggregate.prototype.project = function(arg) {
|
|
|
246
246
|
|
|
247
247
|
if (typeof arg === 'object' && !Array.isArray(arg)) {
|
|
248
248
|
Object.keys(arg).forEach(function(field) {
|
|
249
|
+
// `fields[field] = ...` would set the prototype of `fields`
|
|
250
|
+
if (field === '__proto__') {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
249
253
|
fields[field] = arg[field];
|
|
250
254
|
});
|
|
251
255
|
} else if (arguments.length === 1 && typeof arg === 'string') {
|
package/lib/cast.js
CHANGED
|
@@ -13,8 +13,10 @@ const castString = require('./cast/string');
|
|
|
13
13
|
const castTextSearch = require('./schema/operators/text');
|
|
14
14
|
const get = require('./helpers/get');
|
|
15
15
|
const getDiscriminatorValueFromFilter = require('./helpers/discriminator/getDiscriminatorValueFromFilter');
|
|
16
|
+
const getOwnProperty = require('./helpers/getOwnProperty');
|
|
16
17
|
const getSchemaDiscriminatorByValue = require('./helpers/discriminator/getSchemaDiscriminatorByValue');
|
|
17
18
|
const isOperator = require('./helpers/query/isOperator');
|
|
19
|
+
const { logicalOperators } = require('./filters/operators');
|
|
18
20
|
const util = require('util');
|
|
19
21
|
const isObject = require('./helpers/isObject');
|
|
20
22
|
const isMongooseObject = require('./helpers/isMongooseObject');
|
|
@@ -65,7 +67,7 @@ module.exports = function cast(schema, obj, options, context) {
|
|
|
65
67
|
path = paths[i];
|
|
66
68
|
val = obj[path];
|
|
67
69
|
|
|
68
|
-
if (path
|
|
70
|
+
if (logicalOperators.has(path)) {
|
|
69
71
|
if (!Array.isArray(val)) {
|
|
70
72
|
throw new CastError('Array', val, path);
|
|
71
73
|
}
|
|
@@ -289,7 +291,7 @@ module.exports = function cast(schema, obj, options, context) {
|
|
|
289
291
|
}
|
|
290
292
|
}
|
|
291
293
|
|
|
292
|
-
if (schema.nested
|
|
294
|
+
if (getOwnProperty(schema.nested, path)) {
|
|
293
295
|
continue;
|
|
294
296
|
}
|
|
295
297
|
|
package/lib/connection.js
CHANGED
|
@@ -17,6 +17,7 @@ const clone = require('./helpers/clone');
|
|
|
17
17
|
const driver = require('./driver');
|
|
18
18
|
const get = require('./helpers/get');
|
|
19
19
|
const getDefaultBulkwriteResult = require('./helpers/getDefaultBulkwriteResult');
|
|
20
|
+
const getOwnProperty = require('./helpers/getOwnProperty');
|
|
20
21
|
const immediate = require('./helpers/immediate');
|
|
21
22
|
const utils = require('./utils');
|
|
22
23
|
const CreateCollectionsError = require('./error/createCollectionsError');
|
|
@@ -1474,12 +1475,14 @@ Connection.prototype.model = function model(name, schema, collection, options) {
|
|
|
1474
1475
|
|
|
1475
1476
|
const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels };
|
|
1476
1477
|
const opts = Object.assign(defaultOptions, options, { connection: this });
|
|
1477
|
-
|
|
1478
|
+
// Own properties only, so names like 'constructor' or 'toString' don't return built-ins
|
|
1479
|
+
const existingModel = getOwnProperty(this.models, name);
|
|
1480
|
+
if (existingModel && !collection && opts.overwriteModels !== true) {
|
|
1478
1481
|
// model exists but we are not subclassing with custom collection
|
|
1479
|
-
if (schema?.instanceOfSchema && schema !==
|
|
1482
|
+
if (schema?.instanceOfSchema && schema !== existingModel.schema) {
|
|
1480
1483
|
throw new MongooseError.OverwriteModelError(name);
|
|
1481
1484
|
}
|
|
1482
|
-
return
|
|
1485
|
+
return existingModel;
|
|
1483
1486
|
}
|
|
1484
1487
|
|
|
1485
1488
|
let model;
|
|
@@ -1492,7 +1495,7 @@ Connection.prototype.model = function model(name, schema, collection, options) {
|
|
|
1492
1495
|
|
|
1493
1496
|
// only the first model with this name is cached to allow
|
|
1494
1497
|
// for one-offs with custom collection names etc.
|
|
1495
|
-
if (!this.models
|
|
1498
|
+
if (!getOwnProperty(this.models, name)) {
|
|
1496
1499
|
this.models[name] = model;
|
|
1497
1500
|
}
|
|
1498
1501
|
|
|
@@ -1502,9 +1505,9 @@ Connection.prototype.model = function model(name, schema, collection, options) {
|
|
|
1502
1505
|
return model;
|
|
1503
1506
|
}
|
|
1504
1507
|
|
|
1505
|
-
if (
|
|
1508
|
+
if (existingModel && collection) {
|
|
1506
1509
|
// subclassing current model with alternate collection
|
|
1507
|
-
model =
|
|
1510
|
+
model = existingModel;
|
|
1508
1511
|
schema = model.prototype.schema;
|
|
1509
1512
|
const sub = model.__subclass(this, schema, collection);
|
|
1510
1513
|
// do not cache the sub model
|
|
@@ -1512,7 +1515,7 @@ Connection.prototype.model = function model(name, schema, collection, options) {
|
|
|
1512
1515
|
}
|
|
1513
1516
|
|
|
1514
1517
|
if (arguments.length === 1) {
|
|
1515
|
-
model =
|
|
1518
|
+
model = existingModel;
|
|
1516
1519
|
if (!model) {
|
|
1517
1520
|
throw new MongooseError.MissingSchemaError(name);
|
|
1518
1521
|
}
|
|
@@ -1826,7 +1829,7 @@ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
|
|
|
1826
1829
|
*/
|
|
1827
1830
|
|
|
1828
1831
|
/**
|
|
1829
|
-
* Removes the database connection with the given name created with
|
|
1832
|
+
* Removes the database connection with the given name created with `useDb()`.
|
|
1830
1833
|
*
|
|
1831
1834
|
* Throws an error if the database connection was not found.
|
|
1832
1835
|
*
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Precomputed information about which paths in a schema have defaults, so
|
|
5
|
+
* applying defaults doesn't need to iterate over every path in the schema for
|
|
6
|
+
* every document.
|
|
7
|
+
*
|
|
8
|
+
* - `paths` and `schemaTypes` are parallel arrays of every path in the schema
|
|
9
|
+
* that has a default, in `schema.paths` order, excluding map values like `map.$*`.
|
|
10
|
+
* - `defaultsByNestedPath` maps each nested path (e.g. `'a.b'`) to the subset of those paths
|
|
11
|
+
* underneath that nested path, plus `depth`, the number of pieces in the nested path.
|
|
12
|
+
*
|
|
13
|
+
* #### Example:
|
|
14
|
+
*
|
|
15
|
+
* const s = new Schema({
|
|
16
|
+
* name: { type: String, default: 'test' },
|
|
17
|
+
* nested: { a: { type: Number, default: 1 }, b: String }
|
|
18
|
+
* });
|
|
19
|
+
* const cache = s._getDefaultsCache();
|
|
20
|
+
* cache.paths; // [ 'name', 'nested.a', '_id' ]
|
|
21
|
+
* cache.defaultsByNestedPath.get('nested'); // { paths: ['nested.a'], schemaTypes: [...], depth: 1 }
|
|
22
|
+
*
|
|
23
|
+
* @api private
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
class SchemaDefaultsCache {
|
|
27
|
+
constructor(schema) {
|
|
28
|
+
this.paths = [];
|
|
29
|
+
this.schemaTypes = [];
|
|
30
|
+
this.defaultsByNestedPath = new Map();
|
|
31
|
+
|
|
32
|
+
for (const path of Object.keys(schema.paths)) {
|
|
33
|
+
const schemaType = schema.paths[path];
|
|
34
|
+
if (schemaType.defaultValue === undefined) {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const pieces = schemaType.splitPath();
|
|
38
|
+
if (pieces[pieces.length - 1] === '$*') {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
this.paths.push(path);
|
|
42
|
+
this.schemaTypes.push(schemaType);
|
|
43
|
+
|
|
44
|
+
let nestedPath = '';
|
|
45
|
+
for (let i = 0; i < pieces.length - 1; ++i) {
|
|
46
|
+
nestedPath = i === 0 ? pieces[0] : nestedPath + '.' + pieces[i];
|
|
47
|
+
if (schema.nested[nestedPath] !== true) {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
let entry = this.defaultsByNestedPath.get(nestedPath);
|
|
51
|
+
if (entry == null) {
|
|
52
|
+
entry = { paths: [], schemaTypes: [], depth: i + 1 };
|
|
53
|
+
this.defaultsByNestedPath.set(nestedPath, entry);
|
|
54
|
+
}
|
|
55
|
+
entry.paths.push(path);
|
|
56
|
+
entry.schemaTypes.push(schemaType);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = SchemaDefaultsCache;
|
package/lib/document.js
CHANGED
|
@@ -29,10 +29,12 @@ const firstKey = require('./helpers/firstKey');
|
|
|
29
29
|
const getConstructorName = require('./helpers/getConstructorName');
|
|
30
30
|
const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath');
|
|
31
31
|
const getKeysInSchemaOrder = require('./helpers/schema/getKeysInSchemaOrder');
|
|
32
|
+
const getOwnProperty = require('./helpers/getOwnProperty');
|
|
32
33
|
const getSubdocumentStrictValue = require('./helpers/schema/getSubdocumentStrictValue');
|
|
33
34
|
const handleSpreadDoc = require('./helpers/document/handleSpreadDoc');
|
|
34
35
|
const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
|
|
35
36
|
const isExclusive = require('./helpers/projection/isExclusive');
|
|
37
|
+
const isMongooseDocument = require('./helpers/isMongooseDocument');
|
|
36
38
|
const isPathExcluded = require('./helpers/projection/isPathExcluded');
|
|
37
39
|
const inspect = require('util').inspect;
|
|
38
40
|
const internalToObjectOptions = require('./options').internalToObjectOptions;
|
|
@@ -73,6 +75,13 @@ const VERSION_WHERE = 1;
|
|
|
73
75
|
const VERSION_INC = 2;
|
|
74
76
|
const VERSION_ALL = VERSION_WHERE | VERSION_INC;
|
|
75
77
|
|
|
78
|
+
/*!
|
|
79
|
+
* Document internals that don't start with `$`. `isNew` is a getter/setter
|
|
80
|
+
* for `$isNew`.
|
|
81
|
+
*/
|
|
82
|
+
|
|
83
|
+
const documentInternalKeys = new Set(['_doc', '__parentArray', '__index', 'isNew']);
|
|
84
|
+
|
|
76
85
|
/**
|
|
77
86
|
* The core Mongoose document constructor. You should not call this directly,
|
|
78
87
|
* the Mongoose [Model constructor](./api/model.html#Model()) calls this for you.
|
|
@@ -208,9 +217,9 @@ function Document(obj, fields, options) {
|
|
|
208
217
|
const keys = Object.keys(this._doc);
|
|
209
218
|
|
|
210
219
|
keys.forEach(function(key) {
|
|
211
|
-
// Avoid methods, virtuals, existing fields, and
|
|
212
|
-
// Mongoose internals.
|
|
213
|
-
if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) &&
|
|
220
|
+
// Avoid methods, virtuals, existing fields, and internals like `$__` or `_doc`. The latter is
|
|
221
|
+
// to avoid overwriting Mongoose internals.
|
|
222
|
+
if (!(key in schema.tree) && !(key in schema.methods) && !(key in schema.virtuals) && canSetAdhocKey(key)) {
|
|
214
223
|
defineKey({ prop: key, subprops: null, prototype: _this });
|
|
215
224
|
}
|
|
216
225
|
});
|
|
@@ -495,34 +504,22 @@ function $applyDefaultsToNested(val, path, doc) {
|
|
|
495
504
|
return;
|
|
496
505
|
}
|
|
497
506
|
|
|
498
|
-
|
|
507
|
+
// Paths underneath `path` with defaults, excluding map value paths (`$*`)
|
|
508
|
+
const nestedDefaults = doc.$__schema._getDefaultsCache().defaultsByNestedPath.get(path);
|
|
509
|
+
if (nestedDefaults == null) {
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
const { paths, schemaTypes, depth: numPathPieces } = nestedDefaults;
|
|
499
513
|
const plen = paths.length;
|
|
500
514
|
|
|
501
|
-
const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.');
|
|
502
|
-
|
|
503
515
|
for (let i = 0; i < plen; ++i) {
|
|
504
|
-
let curPath = '';
|
|
505
516
|
const p = paths[i];
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
continue;
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
const type = doc.$__schema.paths[p];
|
|
512
|
-
const pieces = type.splitPath().slice(pathPieces.length);
|
|
517
|
+
const type = schemaTypes[i];
|
|
518
|
+
const pieces = type.splitPath();
|
|
513
519
|
const len = pieces.length;
|
|
514
520
|
|
|
515
|
-
if (type.defaultValue === void 0) {
|
|
516
|
-
continue;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
521
|
let cur = val;
|
|
520
|
-
|
|
521
|
-
for (let j = 0; j < len; ++j) {
|
|
522
|
-
if (cur == null) {
|
|
523
|
-
break;
|
|
524
|
-
}
|
|
525
|
-
|
|
522
|
+
for (let j = numPathPieces; j < len; ++j) {
|
|
526
523
|
const piece = pieces[j];
|
|
527
524
|
|
|
528
525
|
if (j === len - 1) {
|
|
@@ -534,18 +531,20 @@ function $applyDefaultsToNested(val, path, doc) {
|
|
|
534
531
|
const def = type.getDefault(doc, false);
|
|
535
532
|
if (def !== void 0) {
|
|
536
533
|
cur[piece] = def;
|
|
534
|
+
doc.$__.activePaths.default(p);
|
|
537
535
|
}
|
|
538
536
|
} catch (err) {
|
|
539
|
-
doc.invalidate(
|
|
540
|
-
break;
|
|
537
|
+
doc.invalidate(p, err);
|
|
541
538
|
}
|
|
542
|
-
|
|
543
539
|
break;
|
|
544
540
|
}
|
|
545
541
|
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
542
|
+
if (cur[piece] == null) {
|
|
543
|
+
cur[piece] = {};
|
|
544
|
+
} else if (typeof cur[piece] !== 'object') {
|
|
545
|
+
// Don't overwrite user-specified primitives with an object
|
|
546
|
+
break;
|
|
547
|
+
}
|
|
549
548
|
cur = cur[piece];
|
|
550
549
|
}
|
|
551
550
|
}
|
|
@@ -760,7 +759,7 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
760
759
|
throw new ObjectExpectedError(self.$basePath, obj);
|
|
761
760
|
}
|
|
762
761
|
|
|
763
|
-
if (obj
|
|
762
|
+
if (isMongooseDocument(obj)) {
|
|
764
763
|
obj = obj._doc;
|
|
765
764
|
}
|
|
766
765
|
const keys = Object.keys(obj);
|
|
@@ -804,9 +803,9 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
804
803
|
}
|
|
805
804
|
if (!doc[i]) {
|
|
806
805
|
doc[i] = {};
|
|
807
|
-
if (!strict && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals)) {
|
|
806
|
+
if (!strict && !prefix && !(i in docSchema.tree) && !(i in docSchema.methods) && !(i in docSchema.virtuals) && canSetAdhocKey(i)) {
|
|
808
807
|
self[i] = doc[i];
|
|
809
|
-
} else if (opts?.virtuals && (
|
|
808
|
+
} else if (opts?.virtuals && Object.hasOwn(docSchema.virtuals, i)) {
|
|
810
809
|
self[i] = doc[i];
|
|
811
810
|
}
|
|
812
811
|
}
|
|
@@ -821,8 +820,10 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
821
820
|
}
|
|
822
821
|
doc[i] = value;
|
|
823
822
|
if (!strict && !prefix) {
|
|
824
|
-
|
|
825
|
-
|
|
823
|
+
if (canSetAdhocKey(i)) {
|
|
824
|
+
self[i] = value;
|
|
825
|
+
}
|
|
826
|
+
} else if (opts?.virtuals && Object.hasOwn(docSchema.virtuals, i)) {
|
|
826
827
|
self[i] = value;
|
|
827
828
|
} else if (opts?.strict === 'throw') {
|
|
828
829
|
// Only use strict: 'throw' semantics if explicit `strict: 'throw'` option
|
|
@@ -839,7 +840,7 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
839
840
|
if (value === null) {
|
|
840
841
|
doc[i] = schemaType._castNullish(null);
|
|
841
842
|
} else if (value !== undefined) {
|
|
842
|
-
const wasPopulated = value
|
|
843
|
+
const wasPopulated = isMongooseDocument(value) ? value.$__.wasPopulated : null;
|
|
843
844
|
|
|
844
845
|
if (schemaType && !wasPopulated && !opts.hydratedPopulatedDocs) {
|
|
845
846
|
try {
|
|
@@ -862,10 +863,10 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
862
863
|
} else if (schemaType && opts.hydratedPopulatedDocs) {
|
|
863
864
|
doc[i] = schemaType.cast(value, self, true, undefined, { hydratedPopulatedDocs: true });
|
|
864
865
|
|
|
865
|
-
if (doc[i]
|
|
866
|
+
if (isMongooseDocument(doc[i]) && doc[i].$__.wasPopulated) {
|
|
866
867
|
self.$populated(path, doc[i].$__.wasPopulated.value, doc[i].$__.wasPopulated.options);
|
|
867
|
-
} else if (Array.isArray(doc[i]) && doc[i].length && doc[i][0]
|
|
868
|
-
self.$populated(path, doc[i].map(populatedDoc => populatedDoc
|
|
868
|
+
} else if (Array.isArray(doc[i]) && doc[i].length && isMongooseDocument(doc[i][0]) && doc[i][0].$__.wasPopulated) {
|
|
869
|
+
self.$populated(path, doc[i].map(populatedDoc => isMongooseDocument(populatedDoc) ? populatedDoc.$__.wasPopulated?.value : null).filter(val => val != null), doc[i][0].$__.wasPopulated.options);
|
|
869
870
|
}
|
|
870
871
|
} else {
|
|
871
872
|
doc[i] = value;
|
|
@@ -881,6 +882,21 @@ function init(self, obj, doc, opts, prefix) {
|
|
|
881
882
|
}
|
|
882
883
|
}
|
|
883
884
|
|
|
885
|
+
/**
|
|
886
|
+
* Returns true if `key`, a field that isn't in the schema, can be set as a
|
|
887
|
+
* property on a document with `strict: false`. Fields must not overwrite
|
|
888
|
+
* document internals: keys that start with `$`, like `$__`, and the internals
|
|
889
|
+
* in `documentInternalKeys`.
|
|
890
|
+
*
|
|
891
|
+
* @param {string} key
|
|
892
|
+
* @return {boolean}
|
|
893
|
+
* @api private
|
|
894
|
+
*/
|
|
895
|
+
|
|
896
|
+
function canSetAdhocKey(key) {
|
|
897
|
+
return !key.startsWith('$') && !documentInternalKeys.has(key);
|
|
898
|
+
}
|
|
899
|
+
|
|
884
900
|
/**
|
|
885
901
|
* Sends an updateOne command with this document `_id` as the query selector.
|
|
886
902
|
*
|
|
@@ -1399,7 +1415,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
|
|
1399
1415
|
// a single nested doc. That's to make sure we get the correct context.
|
|
1400
1416
|
// Otherwise we would double-call the setter, see gh-7196.
|
|
1401
1417
|
let setterContext = this;
|
|
1402
|
-
if (this.$__schema.singleNestedPaths
|
|
1418
|
+
if (getOwnProperty(this.$__schema.singleNestedPaths, path) != null && parts.length > 1) {
|
|
1403
1419
|
setterContext = getDeepestSubdocumentForPath(this, parts, this.schema);
|
|
1404
1420
|
}
|
|
1405
1421
|
const setterOptions = { path };
|
|
@@ -1410,7 +1426,7 @@ Document.prototype.$set = function $set(path, val, type, options) {
|
|
|
1410
1426
|
}
|
|
1411
1427
|
|
|
1412
1428
|
// Track populated paths of documents in a document array
|
|
1413
|
-
if (schema.$isMongooseDocumentArray && Array.isArray(val) && val[0]
|
|
1429
|
+
if (schema.$isMongooseDocumentArray && Array.isArray(val) && isMongooseDocument(val[0]) && val[0].$__.populated != null) {
|
|
1414
1430
|
const populated = val[0].$__.populated;
|
|
1415
1431
|
for (const populatedPath of Object.keys(populated)) {
|
|
1416
1432
|
this.$populated(path + '.' + populatedPath,
|
|
@@ -1709,7 +1725,7 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
|
|
|
1709
1725
|
// objects. Document properties are getters on the prototype, so read raw values
|
|
1710
1726
|
// from `_doc`. Nested properties have a `$__` but their `_doc` is their parent's
|
|
1711
1727
|
// `_doc`.
|
|
1712
|
-
const raw = obj
|
|
1728
|
+
const raw = isMongooseDocument(obj) && !obj.$__isNested ? obj._doc : obj;
|
|
1713
1729
|
if (!isMap && !Object.hasOwn(raw, parts[i]) && parts[i] in obj) {
|
|
1714
1730
|
return;
|
|
1715
1731
|
}
|
|
@@ -2201,7 +2217,7 @@ Document.prototype.modifiedPaths = function(options) {
|
|
|
2201
2217
|
const subPath = path + '.' + ii;
|
|
2202
2218
|
if (!result.has(subPath)) {
|
|
2203
2219
|
result.add(subPath);
|
|
2204
|
-
if (cur[ii]
|
|
2220
|
+
if (isMongooseDocument(cur[ii])) {
|
|
2205
2221
|
const modified = cur[ii].modifiedPaths();
|
|
2206
2222
|
let iii = 0;
|
|
2207
2223
|
const iiiLen = modified.length;
|
|
@@ -2397,7 +2413,7 @@ Document.prototype.isDirectModified = function(path) {
|
|
|
2397
2413
|
for (let i = 0; i < pieces.length - 1; ++i) {
|
|
2398
2414
|
const subpath = pieces.slice(0, i + 1).join('.');
|
|
2399
2415
|
const subdoc = this.$get(subpath);
|
|
2400
|
-
if (subdoc
|
|
2416
|
+
if (isMongooseDocument(subdoc) && subdoc.isDirectModified(pieces.slice(i + 1).join('.'))) {
|
|
2401
2417
|
return true;
|
|
2402
2418
|
}
|
|
2403
2419
|
}
|
|
@@ -2787,7 +2803,7 @@ Document.prototype.validate = async function validate(pathsToValidate, options)
|
|
|
2787
2803
|
let pop;
|
|
2788
2804
|
if ((pop = _this.$populated(path))) {
|
|
2789
2805
|
val = pop;
|
|
2790
|
-
} else if (val
|
|
2806
|
+
} else if (isMongooseDocument(val) && val.$__.wasPopulated) {
|
|
2791
2807
|
// Array paths, like `somearray.1`, do not show up as populated with `$populated()`,
|
|
2792
2808
|
// so in that case pull out the document's id
|
|
2793
2809
|
val = val._doc._id;
|
|
@@ -3091,7 +3107,7 @@ function _getPathsToValidate(doc, pathsToValidate, pathsToSkip) {
|
|
|
3091
3107
|
// Set visits entries added during iteration, so this same loop also resolves
|
|
3092
3108
|
// nested objects several levels deep.
|
|
3093
3109
|
for (const path of paths) {
|
|
3094
|
-
if (!schema.nested
|
|
3110
|
+
if (!getOwnProperty(schema.nested, path)) {
|
|
3095
3111
|
continue;
|
|
3096
3112
|
}
|
|
3097
3113
|
paths.delete(path);
|
|
@@ -3717,7 +3733,7 @@ function _checkImmutableSubpaths(subdoc, schematype, priorVal) {
|
|
|
3717
3733
|
* @param {number|string} [options.w] set the [write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
|
|
3718
3734
|
* @param {boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern)
|
|
3719
3735
|
* @param {number} [options.wtimeout] sets a [timeout for the write concern](https://www.mongodb.com/docs/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](https://mongoosejs.com/docs/guide.html#writeConcern).
|
|
3720
|
-
* @param {boolean} [options.checkKeys=
|
|
3736
|
+
* @param {boolean} [options.checkKeys=false] if `true`, the MongoDB driver rejects keys that start with '$' or contain '.' when this `save()` inserts a new document. Leave it off when saving changes to an existing document: the driver also checks update operators like `$set`, so the update fails. See [restrictions on field names](https://www.mongodb.com/docs/manual/reference/limits/#Restrictions-on-Field-Names)
|
|
3721
3737
|
* @param {boolean} [options.timestamps=true] if `false` and [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this `save()`.
|
|
3722
3738
|
* @param {Array} [options.pathsToSave] An array of paths that tell mongoose to only validate and save the paths in `pathsToSave`.
|
|
3723
3739
|
* @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
|
|
@@ -4046,19 +4062,19 @@ Document.prototype.$getAllSubdocs = function(options) {
|
|
|
4046
4062
|
if (val == null) {
|
|
4047
4063
|
continue;
|
|
4048
4064
|
}
|
|
4049
|
-
if (val
|
|
4065
|
+
if (isMongooseDocument(val)) {
|
|
4050
4066
|
newSubdocs.push(val);
|
|
4051
4067
|
}
|
|
4052
4068
|
if (Array.isArray(val)) {
|
|
4053
4069
|
for (const el of val) {
|
|
4054
|
-
if (el
|
|
4070
|
+
if (isMongooseDocument(el)) {
|
|
4055
4071
|
newSubdocs.push(el);
|
|
4056
4072
|
}
|
|
4057
4073
|
}
|
|
4058
4074
|
}
|
|
4059
4075
|
if (val instanceof Map) {
|
|
4060
4076
|
for (const el of val.values()) {
|
|
4061
|
-
if (el
|
|
4077
|
+
if (isMongooseDocument(el)) {
|
|
4062
4078
|
newSubdocs.push(el);
|
|
4063
4079
|
}
|
|
4064
4080
|
}
|
|
@@ -4865,7 +4881,7 @@ Document.prototype.equals = function(doc) {
|
|
|
4865
4881
|
}
|
|
4866
4882
|
|
|
4867
4883
|
const tid = this.$__getValue('_id');
|
|
4868
|
-
const docid = doc
|
|
4884
|
+
const docid = isMongooseDocument(doc) ? doc.$__getValue('_id') : doc;
|
|
4869
4885
|
if (!tid && !docid) {
|
|
4870
4886
|
return deepEqual(this, doc);
|
|
4871
4887
|
}
|
|
@@ -5051,7 +5067,7 @@ Document.prototype.populated = function(path, val, options) {
|
|
|
5051
5067
|
for (let i = 0; i < pieces.length - 1; ++i) {
|
|
5052
5068
|
const subpath = pieces.slice(0, i + 1).join('.');
|
|
5053
5069
|
const subdoc = this.$get(subpath);
|
|
5054
|
-
if (subdoc
|
|
5070
|
+
if (isMongooseDocument(subdoc) && this.$populated(subpath)) {
|
|
5055
5071
|
const rest = pieces.slice(i + 1).join('.');
|
|
5056
5072
|
subdoc.$populated(rest, val, options);
|
|
5057
5073
|
// No need to continue because the above recursion should take care of
|
|
@@ -5363,7 +5379,7 @@ Document.prototype.$__delta = function $__delta(pathsToSave, pathsToSaveSet) {
|
|
|
5363
5379
|
where._id = this._doc._id;
|
|
5364
5380
|
// If `_id` is an object, need to depopulate, but also need to be careful
|
|
5365
5381
|
// because `_id` can technically be null (see gh-6406)
|
|
5366
|
-
if (where?._id
|
|
5382
|
+
if (isMongooseDocument(where?._id)) {
|
|
5367
5383
|
where._id = where._id.toObject({ transform: false, depopulate: true });
|
|
5368
5384
|
}
|
|
5369
5385
|
for (; d < len; ++d) {
|
package/lib/helpers/clone.js
CHANGED
|
@@ -5,10 +5,11 @@ const ObjectId = require('../types/objectid');
|
|
|
5
5
|
const specialProperties = require('./specialProperties');
|
|
6
6
|
const isMongooseObject = require('./isMongooseObject');
|
|
7
7
|
const getFunctionName = require('./getFunctionName');
|
|
8
|
+
const getInheritedProperty = require('./getInheritedProperty');
|
|
8
9
|
const isBsonType = require('./isBsonType');
|
|
9
10
|
const isMongooseArray = require('../types/array/isMongooseArray').isMongooseArray;
|
|
11
|
+
const isMongooseDocument = require('./isMongooseDocument');
|
|
10
12
|
const isObject = require('./isObject');
|
|
11
|
-
const isPOJO = require('./isPOJO');
|
|
12
13
|
const symbols = require('./symbols');
|
|
13
14
|
const trustedSymbol = require('./query/trusted').trustedSymbol;
|
|
14
15
|
const BSON = require('mongodb/lib/bson');
|
|
@@ -52,11 +53,11 @@ function clone(obj, options, isArrayChild) {
|
|
|
52
53
|
if (obj instanceof Binary && obj._subtype === Binary.SUBTYPE_UUID) {
|
|
53
54
|
return obj.toString();
|
|
54
55
|
}
|
|
55
|
-
if (obj
|
|
56
|
+
if (Buffer.isBuffer(obj) && obj.isMongooseBuffer && obj._subtype === Binary.SUBTYPE_UUID) {
|
|
56
57
|
return obj.toUUID().toString();
|
|
57
58
|
}
|
|
58
59
|
}
|
|
59
|
-
if (options.retainDocuments && obj
|
|
60
|
+
if (options.retainDocuments && isMongooseDocument(obj)) {
|
|
60
61
|
const clonedDoc = obj.$clone();
|
|
61
62
|
if (obj.__index != null) {
|
|
62
63
|
clonedDoc.__index = obj.__index;
|
|
@@ -67,7 +68,7 @@ function clone(obj, options, isArrayChild) {
|
|
|
67
68
|
clonedDoc.$__setParent(options.parentDoc ?? obj.$__parent);
|
|
68
69
|
return clonedDoc;
|
|
69
70
|
}
|
|
70
|
-
if (options.retainDocuments && obj
|
|
71
|
+
if (options.retainDocuments && getInheritedProperty(obj, '$isMongooseMap')) {
|
|
71
72
|
const clonedParent = options.parentDoc ?? obj.$__parent;
|
|
72
73
|
const MongooseMap = obj.constructor;
|
|
73
74
|
const ret = new MongooseMap({}, obj.$__path, clonedParent, obj.$__schemaType);
|
|
@@ -78,10 +79,6 @@ function clone(obj, options, isArrayChild) {
|
|
|
78
79
|
}
|
|
79
80
|
}
|
|
80
81
|
|
|
81
|
-
if (isPOJO(obj) && obj.$__ != null && obj._doc != null) {
|
|
82
|
-
return obj._doc;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
82
|
let ret;
|
|
86
83
|
if (options?.json && typeof obj.toJSON === 'function') {
|
|
87
84
|
ret = obj.toJSON(options);
|
|
@@ -97,6 +94,10 @@ function clone(obj, options, isArrayChild) {
|
|
|
97
94
|
if (objConstructor) {
|
|
98
95
|
switch (getFunctionName(objConstructor)) {
|
|
99
96
|
case 'Object':
|
|
97
|
+
// Spread documents (`{ ...doc }`) copy the document's `$__` and `_doc`
|
|
98
|
+
if (getInheritedProperty(obj.$__, 'strictMode') != null && obj._doc != null) {
|
|
99
|
+
return obj._doc;
|
|
100
|
+
}
|
|
100
101
|
return cloneObject(obj, options, isArrayChild);
|
|
101
102
|
case 'Date':
|
|
102
103
|
return new objConstructor(+obj);
|
|
@@ -4,7 +4,7 @@ const isNestedProjection = require('../projection/isNestedProjection');
|
|
|
4
4
|
|
|
5
5
|
module.exports = function applyDefaults(doc, fields, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip, options) {
|
|
6
6
|
// Only paths with a default can modify the doc, so skip iterating over every path in the schema.
|
|
7
|
-
const { paths: pathsWithDefaults, schemaTypes } = doc.$__schema.
|
|
7
|
+
const { paths: pathsWithDefaults, schemaTypes } = doc.$__schema._getDefaultsCache();
|
|
8
8
|
const numPaths = pathsWithDefaults.length;
|
|
9
9
|
const skipParentChangeTracking = options?.skipParentChangeTracking;
|
|
10
10
|
const skipId = doc.$__.skipId;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const clone = require('../../helpers/clone');
|
|
4
4
|
const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol;
|
|
5
5
|
const internalToObjectOptions = require('../../options').internalToObjectOptions;
|
|
6
|
+
const isMongooseDocument = require('../isMongooseDocument');
|
|
6
7
|
const utils = require('../../utils');
|
|
7
8
|
|
|
8
9
|
let Document;
|
|
@@ -181,7 +182,7 @@ function defineKey({ prop, subprops, prototype, prefix, options }) {
|
|
|
181
182
|
return this.$__.getters[path];
|
|
182
183
|
},
|
|
183
184
|
set: function(v) {
|
|
184
|
-
if (v
|
|
185
|
+
if (isMongooseDocument(v) && v.$__isNested) {
|
|
185
186
|
// Convert top-level to POJO, but leave subdocs hydrated so `$set`
|
|
186
187
|
// can handle them. See gh-9293.
|
|
187
188
|
v = v.$__get();
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const getInheritedProperty = require('../getInheritedProperty');
|
|
3
4
|
const utils = require('../../utils');
|
|
4
5
|
|
|
5
6
|
const keysToSkip = new Set(['__index', '__parentArray', '_doc']);
|
|
@@ -11,7 +12,7 @@ const keysToSkip = new Set(['__index', '__parentArray', '_doc']);
|
|
|
11
12
|
*/
|
|
12
13
|
|
|
13
14
|
module.exports = function handleSpreadDoc(v, includeExtraKeys) {
|
|
14
|
-
if (utils.isPOJO(v) && v.$__ != null && v._doc != null) {
|
|
15
|
+
if (utils.isPOJO(v) && getInheritedProperty(v.$__, 'strictMode') != null && v._doc != null) {
|
|
15
16
|
if (includeExtraKeys) {
|
|
16
17
|
const extraKeys = {};
|
|
17
18
|
for (const key of Object.keys(v)) {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the value of `key` on `obj`'s prototype chain, ignoring any own
|
|
5
|
+
* property `key` on `obj`.
|
|
6
|
+
*
|
|
7
|
+
* Use this to check markers that Mongoose defines on prototypes, like
|
|
8
|
+
* `MongooseMap.prototype.$isMongooseMap`. User data, like parsed JSON, BSON, or
|
|
9
|
+
* query strings, can only set own properties, so it can't spoof these markers.
|
|
10
|
+
* Don't use `obj.constructor.prototype` instead: user data can have an own
|
|
11
|
+
* `constructor` property.
|
|
12
|
+
*
|
|
13
|
+
* Getters on the prototype run with the prototype as `this`, so only use this
|
|
14
|
+
* for data properties.
|
|
15
|
+
*
|
|
16
|
+
* @param {any} obj
|
|
17
|
+
* @param {string} key
|
|
18
|
+
* @return {any}
|
|
19
|
+
* @api private
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
module.exports = function getInheritedProperty(obj, key) {
|
|
23
|
+
if (obj == null) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
const proto = Object.getPrototypeOf(obj);
|
|
27
|
+
return proto == null ? undefined : proto[key];
|
|
28
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns `obj[key]` if `key` is an own property of `obj`, `undefined` otherwise.
|
|
5
|
+
*
|
|
6
|
+
* Use this instead of `obj[key]` when `key` may come from user input and `obj`
|
|
7
|
+
* is a plain object lookup table, like `schema.nested` or `schema.virtuals`.
|
|
8
|
+
* Otherwise keys like `toString` or `valueOf` resolve to functions inherited
|
|
9
|
+
* from `Object.prototype`.
|
|
10
|
+
*
|
|
11
|
+
* @param {object} obj
|
|
12
|
+
* @param {string} key
|
|
13
|
+
* @return {any}
|
|
14
|
+
* @api private
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
module.exports = function getOwnProperty(obj, key) {
|
|
18
|
+
return obj != null && Object.hasOwn(obj, key) ? obj[key] : undefined;
|
|
19
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const getInheritedProperty = require('./getInheritedProperty');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Returns true if `v` is a Mongoose document: `v` inherits
|
|
7
|
+
* `Document.prototype.$isMongooseDocumentPrototype`. Use this instead of
|
|
8
|
+
* `v.$__ != null` when `v` may be user data, because user data can contain a
|
|
9
|
+
* `$__` key.
|
|
10
|
+
*
|
|
11
|
+
* Checks the prototype marker rather than using `instanceof`, so documents
|
|
12
|
+
* created by a different copy of Mongoose still count. Spread documents
|
|
13
|
+
* (`{ ...doc }`) are POJOs, so they do **not** count.
|
|
14
|
+
*
|
|
15
|
+
* @param {any} v
|
|
16
|
+
* @return {boolean}
|
|
17
|
+
* @api private
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
module.exports = function isMongooseDocument(v) {
|
|
21
|
+
// Plain property read first: much faster than `getInheritedProperty()` for
|
|
22
|
+
// the common case where `v` isn't a document.
|
|
23
|
+
return v != null && v.$isMongooseDocumentPrototype === true && getInheritedProperty(v, '$isMongooseDocumentPrototype') === true;
|
|
24
|
+
};
|