mongoose 9.11.3 → 9.12.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/schema.js CHANGED
@@ -486,6 +486,9 @@ Schema.prototype._clone = function _clone(Constructor) {
486
486
  s.$globalPluginsApplied = this.$globalPluginsApplied;
487
487
  s.$isRootDiscriminator = this.$isRootDiscriminator;
488
488
  s.$implicitlyCreated = this.$implicitlyCreated;
489
+ if (this.$timestamps != null) {
490
+ s.$timestamps = Object.assign({}, this.$timestamps);
491
+ }
489
492
  s.$id = ++id;
490
493
  s.$originalSchemaId = this.$id;
491
494
 
@@ -1359,6 +1362,8 @@ Schema.prototype.path = function(path, obj) {
1359
1362
  branch[last] = clone(obj);
1360
1363
 
1361
1364
  this.paths[path] = this.interpretAsType(path, obj, this.options);
1365
+ this._pathsWithDefaults = null;
1366
+ this._hasSelectedPaths = undefined;
1362
1367
  const schemaType = this.paths[path];
1363
1368
 
1364
1369
  // If overwriting an existing path, make sure to clear the childSchemas
@@ -1923,6 +1928,50 @@ Schema.prototype.pathsWithTransforms = function pathsWithTransforms(invalidate)
1923
1928
  return this._pathsWithTransforms;
1924
1929
  };
1925
1930
 
1931
+ /**
1932
+ * Returns the paths in this schema that have a default, excluding map values
1933
+ * like `map.$*`, as parallel arrays of paths and schematypes in `schema.paths` order.
1934
+ * This lets `applyDefaults()` skip iterating over every path in the schema for
1935
+ * every document. Computed when the first document is created, and cleared when
1936
+ * compiling or recompiling a model that uses this schema or if paths are added or removed.
1937
+ *
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
+ * @api private
1948
+ * @return {{ paths: string[], schemaTypes: SchemaType[] }}
1949
+ */
1950
+
1951
+ Schema.prototype._getPathsWithDefaults = function _getPathsWithDefaults() {
1952
+ if (this._pathsWithDefaults != null) {
1953
+ return this._pathsWithDefaults;
1954
+ }
1955
+
1956
+ const paths = [];
1957
+ const schemaTypes = [];
1958
+ for (const path of Object.keys(this.paths)) {
1959
+ const schemaType = this.paths[path];
1960
+ if (schemaType.defaultValue === undefined) {
1961
+ continue;
1962
+ }
1963
+ const pieces = schemaType.splitPath();
1964
+ if (pieces[pieces.length - 1] === '$*') {
1965
+ continue;
1966
+ }
1967
+ paths.push(path);
1968
+ schemaTypes.push(schemaType);
1969
+ }
1970
+
1971
+ this._pathsWithDefaults = { paths, schemaTypes };
1972
+ return this._pathsWithDefaults;
1973
+ };
1974
+
1926
1975
  /**
1927
1976
  * Returns indexes from fields and schema-level indexes (cached).
1928
1977
  *
@@ -2653,6 +2702,12 @@ Schema.prototype.virtual = function(name, options) {
2653
2702
  if (name instanceof VirtualType || getConstructorName(name) === 'VirtualType') {
2654
2703
  return this.virtual(name.path, name.options);
2655
2704
  }
2705
+ const parts = name.split('.');
2706
+ for (const part of parts) {
2707
+ if (utils.specialProperties.has(part)) {
2708
+ throw new MongooseError('Cannot set special property `' + part + '` on a schema');
2709
+ }
2710
+ }
2656
2711
  options = new VirtualOptions(options);
2657
2712
 
2658
2713
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
@@ -2754,7 +2809,6 @@ Schema.prototype.virtual = function(name, options) {
2754
2809
  }
2755
2810
 
2756
2811
  const virtuals = this.virtuals;
2757
- const parts = name.split('.');
2758
2812
 
2759
2813
  if (this.pathType(name) === 'real') {
2760
2814
  throw new MongooseError('Virtual path "' + name + '"' +
@@ -2820,6 +2874,8 @@ Schema.prototype.remove = function(path) {
2820
2874
  if (this.path(name) == null && !this.nested[name]) {
2821
2875
  return;
2822
2876
  }
2877
+ this._pathsWithDefaults = null;
2878
+ this._hasSelectedPaths = undefined;
2823
2879
  if (this.nested[name]) {
2824
2880
  const allKeys = Object.keys(this.paths).
2825
2881
  concat(Object.keys(this.nested));
@@ -3232,8 +3288,10 @@ function isArrayFilter(piece) {
3232
3288
  }
3233
3289
 
3234
3290
  /**
3235
- * Called by `compile()` _right before_ compiling. Good for making any changes to
3236
- * the schema that should respect options set by plugins, like `id`
3291
+ * Called by `Model.compile()` _right before_ compiling and by `Model.recompileSchema()`.
3292
+ * Good for making any changes to the schema that should respect options set by plugins,
3293
+ * like `id`. Not called on nested schemas, because those can still change until the
3294
+ * top-level model is compiled.
3237
3295
  * @method _preCompile
3238
3296
  * @memberOf Schema
3239
3297
  * @instance
@@ -3243,10 +3301,67 @@ function isArrayFilter(piece) {
3243
3301
  Schema.prototype._preCompile = function _preCompile() {
3244
3302
  this.plugin(idGetter, { deduplicate: true });
3245
3303
  _precomputeOptimisticConcurrency(this);
3246
- // Cache paths that have transforms
3247
- this.pathsWithTransforms();
3304
+ _clearDerivedPathCaches(this, new Set());
3305
+ this._hasSelectedPaths = _hasSelectedPaths(this, []);
3248
3306
  };
3249
3307
 
3308
+ /*!
3309
+ * Clears caches that are derived from `schema.paths` on `schema` and all of its
3310
+ * nested schemas, because nested schemas can change until the model is compiled.
3311
+ */
3312
+
3313
+ function _clearDerivedPathCaches(schema, seen) {
3314
+ if (seen.has(schema)) {
3315
+ return;
3316
+ }
3317
+ seen.add(schema);
3318
+
3319
+ schema._pathsWithDefaults = null;
3320
+ schema._pathsWithTransforms = undefined;
3321
+ for (const { schema: childSchema } of schema.childSchemas) {
3322
+ _clearDerivedPathCaches(childSchema, seen);
3323
+ }
3324
+ for (const discriminatorSchema of Object.values(schema.discriminators ?? {})) {
3325
+ _clearDerivedPathCaches(discriminatorSchema, seen);
3326
+ }
3327
+ }
3328
+
3329
+ /*!
3330
+ * Returns true if any path in `schema`, including paths in nested schemas,
3331
+ * has a schema-level `select` option. If not, `applyPaths()` can skip walking
3332
+ * the schema on every query. Mirrors the paths that `applyPaths()` checks.
3333
+ */
3334
+
3335
+ function _hasSelectedPaths(schema, stack) {
3336
+ // avoid recursion
3337
+ if (stack.includes(schema)) {
3338
+ return false;
3339
+ }
3340
+ stack.push(schema);
3341
+
3342
+ for (const path of Object.keys(schema.paths)) {
3343
+ const type = schema.paths[path];
3344
+ if (type.$isSchemaMap || path.endsWith('.$*')) {
3345
+ if (type.options?.select === false) {
3346
+ return true;
3347
+ }
3348
+ continue;
3349
+ }
3350
+ if (typeof type.selected === 'boolean') {
3351
+ return true;
3352
+ }
3353
+ if (type.$isMongooseArray && !type.$isMongooseDocumentArray && typeof type.embeddedSchemaType?.selected === 'boolean') {
3354
+ return true;
3355
+ }
3356
+ if (type.schema && _hasSelectedPaths(type.schema, stack)) {
3357
+ return true;
3358
+ }
3359
+ }
3360
+
3361
+ stack.pop();
3362
+ return false;
3363
+ }
3364
+
3250
3365
  /*!
3251
3366
  * Build precomputed path tries for optimisticConcurrency include/exclude so
3252
3367
  * that lookups at save time are a single trie walk that handles nested paths
@@ -74,8 +74,11 @@ StateMachine.prototype._changeState = function _changeState(path, nextState) {
74
74
  }
75
75
 
76
76
  this.paths[path] = nextState;
77
- this.states[nextState] = this.states[nextState] || {};
78
- this.states[nextState][path] = true;
77
+ let bucket = this.states[nextState];
78
+ if (bucket == null) {
79
+ bucket = this.states[nextState] = {};
80
+ }
81
+ bucket[path] = true;
79
82
  };
80
83
 
81
84
  /*!
@@ -9,6 +9,7 @@ const internalToObjectOptions = require('../../../options').internalToObjectOpti
9
9
  const mpath = require('mpath');
10
10
  const utils = require('../../../utils');
11
11
  const isBsonType = require('../../../helpers/isBsonType');
12
+ const UUID = require('mongodb/lib/bson').UUID;
12
13
 
13
14
  const arrayAtomicsBackupSymbol = require('../../../helpers/symbols').arrayAtomicsBackupSymbol;
14
15
  const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol;
@@ -541,7 +542,9 @@ const methods = {
541
542
  */
542
543
 
543
544
  indexOf(obj, fromIndex) {
544
- if (isBsonType(obj, 'ObjectId')) {
545
+ // Compare ObjectIds and UUIDs by their string form, since two instances
546
+ // with the same value are not `==`
547
+ if (isBsonType(obj, 'ObjectId') || obj instanceof UUID) {
545
548
  obj = obj.toString();
546
549
  }
547
550
  // Compare dates by timestamp like `addToSet()` does, so `pull()` works on date arrays
@@ -8,6 +8,7 @@ const EventEmitter = require('events').EventEmitter;
8
8
  const Subdocument = require('./subdocument');
9
9
  const utils = require('../utils');
10
10
 
11
+ const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
11
12
  const documentArrayParent = require('../helpers/symbols').documentArrayParent;
12
13
 
13
14
  /**
@@ -23,25 +24,26 @@ const documentArrayParent = require('../helpers/symbols').documentArrayParent;
23
24
  */
24
25
 
25
26
  function ArraySubdocument(obj, parentArr, skipId, fields, index) {
27
+ let parent;
26
28
  if (utils.isMongooseDocumentArray(parentArr)) {
27
29
  this.__parentArray = parentArr;
28
- this[documentArrayParent] = parentArr.$parent();
30
+ parent = parentArr[arrayParentSymbol];
29
31
  } else {
30
32
  this.__parentArray = undefined;
31
- this[documentArrayParent] = undefined;
32
33
  }
34
+ this[documentArrayParent] = parent;
33
35
  this.$setIndex(index);
34
- this.$__parent = this[documentArrayParent];
36
+ this.$__parent = parent;
35
37
 
36
- let options;
38
+ const options = { isNew: true };
39
+ if (parent != null && 'defaults' in parent.$__) {
40
+ options.defaults = parent.$__.defaults;
41
+ }
37
42
  if (typeof skipId === 'object' && skipId != null) {
38
- options = { isNew: true, ...skipId };
39
- skipId = undefined;
40
- } else {
41
- options = { isNew: true };
43
+ Object.assign(options, skipId);
42
44
  }
43
45
 
44
- Subdocument.call(this, obj, fields, this[documentArrayParent], options);
46
+ Subdocument.call(this, obj, fields, null, options);
45
47
  }
46
48
 
47
49
  /*!
@@ -2,6 +2,7 @@
2
2
 
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
+ const getDiscriminatorByKey = require('../../../helpers/discriminator/getDiscriminatorByKey');
5
6
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
6
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
7
8
  const utils = require('../../../utils');
@@ -93,9 +94,11 @@ const methods = {
93
94
  Constructor.schema &&
94
95
  Constructor.schema.options &&
95
96
  Constructor.schema.options.discriminatorKey) {
96
- if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
97
- Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
98
- Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
97
+ const discriminator = typeof value[Constructor.schema.options.discriminatorKey] === 'string' ?
98
+ getDiscriminatorByKey(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]) :
99
+ null;
100
+ if (discriminator) {
101
+ Constructor = discriminator;
99
102
  } else {
100
103
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, value[Constructor.schema.options.discriminatorKey]);
101
104
  if (constructorByValue) {
@@ -414,9 +417,11 @@ const methods = {
414
417
  Constructor.schema &&
415
418
  Constructor.schema.options &&
416
419
  Constructor.schema.options.discriminatorKey) {
417
- if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
418
- Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
419
- Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
420
+ const discriminator = typeof obj[Constructor.schema.options.discriminatorKey] === 'string' ?
421
+ getDiscriminatorByKey(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]) :
422
+ null;
423
+ if (discriminator) {
424
+ Constructor = discriminator;
420
425
  } else {
421
426
  const constructorByValue = getDiscriminatorByValue(Constructor.discriminators, obj[Constructor.schema.options.discriminatorKey]);
422
427
  if (constructorByValue) {
package/lib/types/map.js CHANGED
@@ -65,6 +65,22 @@ class MongooseMap extends Map {
65
65
  return this.$__schemaType.applyGetters(super.get(key), this.$__parent);
66
66
  }
67
67
 
68
+ /**
69
+ * Overwrites native Map's `has()` function to support ObjectIds as keys.
70
+ *
71
+ * @api public
72
+ * @method has
73
+ * @memberOf Map
74
+ */
75
+
76
+ has(key) {
77
+ if (isBsonType(key, 'ObjectId')) {
78
+ key = key.toString();
79
+ }
80
+
81
+ return super.has(key);
82
+ }
83
+
68
84
  /**
69
85
  * Overwrites native Map's `set()` function to support setters, `populate()`,
70
86
  * and change tracking. Note that Mongoose maps _only_ support strings and
@@ -28,7 +28,11 @@ function Subdocument(value, fields, parent, options) {
28
28
  }
29
29
  Document.call(this, value, fields, options);
30
30
 
31
- delete this.$__.priorDoc;
31
+ // `priorDoc` is only needed during construction, so release the reference.
32
+ // Set to undefined rather than `delete` to keep `$__` out of dictionary mode.
33
+ if (this.$__.priorDoc !== undefined) {
34
+ this.$__.priorDoc = undefined;
35
+ }
32
36
  }
33
37
 
34
38
  Subdocument.prototype = Object.create(Document.prototype);
package/lib/utils.js CHANGED
@@ -926,6 +926,12 @@ exports.mergeClone = function(to, fromObj) {
926
926
  if (specialProperties.has(key)) {
927
927
  continue;
928
928
  }
929
+ // Skip inherited properties like `Object.prototype.toString` to avoid setting
930
+ // properties on shared objects. Document properties are getters on the
931
+ // prototype, so check `_doc`.
932
+ if (!Object.hasOwn(to.$__ == null ? to : to._doc, key) && key in to) {
933
+ continue;
934
+ }
929
935
  if (typeof to[key] === 'undefined') {
930
936
  to[key] = clone(fromObj[key], {
931
937
  transform: false,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "9.11.3",
4
+ "version": "9.12.0",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -22,16 +22,16 @@
22
22
  "dependencies": {
23
23
  "@standard-schema/spec": "^1.1.0",
24
24
  "kareem": "3.4.1",
25
- "mongodb": "~7.7",
25
+ "mongodb": "~7.8",
26
26
  "mpath": "0.9.0",
27
- "mquery": "6.0.0",
27
+ "mquery": "6.0.1",
28
28
  "ms": "2.1.3",
29
- "sift": "17.1.3"
29
+ "sift": "17.1.4"
30
30
  },
31
31
  "devDependencies": {
32
- "@ark/attest": "0.56.5",
32
+ "@ark/attest": "0.58.0",
33
33
  "@eslint/js": "^9.39.3",
34
- "@mongodb-js/mongodb-downloader": "^2.0.2",
34
+ "@mongodb-js/mongodb-downloader": "^3.0.5",
35
35
  "@types/node": "^20.19.0",
36
36
  "acquit": "1.4.0",
37
37
  "acquit-ignore": "0.2.2",
@@ -40,20 +40,19 @@
40
40
  "c8": "12.0.0",
41
41
  "cheerio": "1.2.0",
42
42
  "dox": "1.0.0",
43
- "eslint": "10.11.0",
43
+ "eslint": "10.13.0",
44
44
  "eslint-plugin-mocha-no-only": "1.2.0",
45
- "express": "5.2.1",
45
+ "express": "5.3.0",
46
46
  "fs-extra": "~11.4.0",
47
- "glob": "^13.0.6",
48
47
  "globals": "^17.4.0",
49
48
  "highlight.js": "11.12.0",
50
49
  "linkinator": "8.x",
51
50
  "lodash.isequal": "4.5.0",
52
51
  "lodash.isequalwith": "4.4.0",
53
- "markdownlint-cli2": "0.23.3",
54
- "marked": "18.0.14",
52
+ "markdownlint-cli2": "0.24.0",
53
+ "marked": "18.1.2",
55
54
  "mkdirp": "^3.0.1",
56
- "mocha": "12.0.2",
55
+ "mocha": "12.0.3",
57
56
  "moment": "2.31.0",
58
57
  "mongodb-client-encryption": "^7.2.0",
59
58
  "mongodb-memory-server": "11.3.0",
@@ -64,18 +63,18 @@
64
63
  "tstyche": "^7.0.0",
65
64
  "typescript": "5.9.3",
66
65
  "typescript-eslint": "^8.31.1",
67
- "uuid": "14.0.2",
68
- "xss": "1.0.15"
66
+ "uuid": "14.0.3",
67
+ "xss": "1.0.17"
69
68
  },
70
69
  "directories": {
71
70
  "lib": "./lib/mongoose"
72
71
  },
73
72
  "scripts": {
74
73
  "docs:clean": "npm run docs:clean:stable",
75
- "docs:clean:stable": "rm -rf index.html && rm -rf ./docs/*.html && rm -rf ./docs/api && rm -rf ./docs/tutorials/*.html && rm -rf ./docs/typescript/*.html && rm -rf ./docs/*.html && rm -rf ./docs/source/_docs && rm -rf ./tmp",
74
+ "docs:clean:stable": "rm -rf index.html && rm -rf ./docs/*.html && rm -rf ./docs/api && rm -rf ./docs/tutorials/*.html && rm -rf ./docs/typescript/*.html && rm -rf ./docs/production/*.html && rm -rf ./docs/*.html && rm -rf ./docs/source/_docs && rm -rf ./tmp",
76
75
  "docs:clean:5x": "rm -rf index.html && rm -rf ./docs/5.x && rm -rf ./docs/source/_docs && rm -rf ./tmp",
77
76
  "docs:clean:6x": "rm -rf index.html && rm -rf ./docs/6.x && rm -rf ./docs/source/_docs && rm -rf ./tmp",
78
- "docs:copy:tmp": "mkdirp ./tmp/docs/css && mkdirp ./tmp/docs/js && mkdirp ./tmp/docs/images && mkdirp ./tmp/docs/tutorials && mkdirp ./tmp/docs/typescript && mkdirp ./tmp/docs/api && ncp ./docs/css ./tmp/docs/css --filter=.css$ && ncp ./docs/js ./tmp/docs/js --filter=.js$ && ncp ./docs/images ./tmp/docs/images && ncp ./docs/tutorials ./tmp/docs/tutorials && ncp ./docs/typescript ./tmp/docs/typescript && ncp ./docs/api ./tmp/docs/api && cp index.html ./tmp && cp docs/*.html ./tmp/docs/",
77
+ "docs:copy:tmp": "mkdirp ./tmp/docs/css && mkdirp ./tmp/docs/js && mkdirp ./tmp/docs/images && mkdirp ./tmp/docs/tutorials && mkdirp ./tmp/docs/typescript && mkdirp ./tmp/docs/production && mkdirp ./tmp/docs/api && ncp ./docs/css ./tmp/docs/css --filter=.css$ && ncp ./docs/js ./tmp/docs/js --filter=.js$ && ncp ./docs/images ./tmp/docs/images && ncp ./docs/tutorials ./tmp/docs/tutorials && ncp ./docs/typescript ./tmp/docs/typescript && ncp ./docs/production ./tmp/docs/production && ncp ./docs/api ./tmp/docs/api && cp index.html ./tmp && cp docs/*.html ./tmp/docs/",
79
78
  "docs:copy:tmp:5x": "rm -rf ./docs/5.x && ncp ./tmp ./docs/5.x",
80
79
  "docs:copy:tmp:6x": "rm -rf ./docs/6.x && ncp ./tmp ./docs/6.x",
81
80
  "docs:generate": "node ./scripts/website.js",
package/types/types.d.ts CHANGED
@@ -77,6 +77,18 @@ declare module 'mongoose' {
77
77
  }
78
78
 
79
79
  class Map<V> extends global.Map<string, V> {
80
+ /** Returns the value for `key`, applying getters unless `options.getters` is `false`. ObjectId keys are converted to strings. */
81
+ get(key: string | ObjectId, options?: { getters?: boolean }): V | undefined;
82
+
83
+ /** Returns `true` if the map contains `key`. ObjectId keys are converted to strings. */
84
+ has(key: string | ObjectId): boolean;
85
+
86
+ /** Sets `key` to `value`, applying setters and change tracking. ObjectId keys are converted to strings. */
87
+ set(key: string | ObjectId, value: V): this;
88
+
89
+ /** Removes `key` from the map with change tracking. ObjectId keys are converted to strings. */
90
+ delete(key: string | ObjectId): boolean;
91
+
80
92
  /** Converts a Mongoose map into a vanilla JavaScript map. */
81
93
  toObject(options?: ToObjectOptions & { flattenMaps?: boolean }): any;
82
94
  }