mongoose 9.11.4 → 9.12.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/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
  *
@@ -2825,6 +2874,8 @@ Schema.prototype.remove = function(path) {
2825
2874
  if (this.path(name) == null && !this.nested[name]) {
2826
2875
  return;
2827
2876
  }
2877
+ this._pathsWithDefaults = null;
2878
+ this._hasSelectedPaths = undefined;
2828
2879
  if (this.nested[name]) {
2829
2880
  const allKeys = Object.keys(this.paths).
2830
2881
  concat(Object.keys(this.nested));
@@ -3237,8 +3288,10 @@ function isArrayFilter(piece) {
3237
3288
  }
3238
3289
 
3239
3290
  /**
3240
- * Called by `compile()` _right before_ compiling. Good for making any changes to
3241
- * 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.
3242
3295
  * @method _preCompile
3243
3296
  * @memberOf Schema
3244
3297
  * @instance
@@ -3248,10 +3301,67 @@ function isArrayFilter(piece) {
3248
3301
  Schema.prototype._preCompile = function _preCompile() {
3249
3302
  this.plugin(idGetter, { deduplicate: true });
3250
3303
  _precomputeOptimisticConcurrency(this);
3251
- // Cache paths that have transforms
3252
- this.pathsWithTransforms();
3304
+ _clearDerivedPathCaches(this, new Set());
3305
+ this._hasSelectedPaths = _hasSelectedPaths(this, []);
3253
3306
  };
3254
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
+
3255
3365
  /*!
3256
3366
  * Build precomputed path tries for optimisticConcurrency include/exclude so
3257
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
@@ -740,8 +743,7 @@ const methods = {
740
743
  if (isOverwrite) {
741
744
  atomic.$each = values;
742
745
 
743
- if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
744
- atomics.$push.$position != atomic.$position) {
746
+ if (_cannotMergePush(atomics.$push, atomic)) {
745
747
  if (atomic.$position != null) {
746
748
  [].splice.apply(arr, [atomic.$position, 0].concat(values));
747
749
  ret = arr.length;
@@ -759,9 +761,13 @@ const methods = {
759
761
  } else {
760
762
  atomic = values;
761
763
  ret = _basePush.apply(arr, values);
764
+ if (atomics.$push?.$position != null) {
765
+ this._registerAtomic('$set', this);
766
+ }
762
767
  }
763
768
 
764
- this._registerAtomic('$push', atomic);
769
+ // add to a pending `$each` instead of replacing it (gh-16618)
770
+ this._registerAtomic('$push', atomics.$push?.$each?.length ? values : atomic);
765
771
 
766
772
  return ret;
767
773
  },
@@ -1074,6 +1080,18 @@ function _depopulateIfNecessary(arr, docs) {
1074
1080
  }
1075
1081
  }
1076
1082
 
1083
+ /*!
1084
+ * A `{ $each }` push can only join a pending `$push` when neither has
1085
+ * `$position`, `$slice` or `$sort` (gh-14244, gh-16618)
1086
+ */
1087
+
1088
+ function _cannotMergePush(pending, atomic) {
1089
+ if (!pending?.$each?.length) {
1090
+ return false;
1091
+ }
1092
+ return [pending, atomic].some(push => push.$position != null || push.$slice != null || push.$sort != null);
1093
+ }
1094
+
1077
1095
  const returnVanillaArrayMethods = [
1078
1096
  'filter',
1079
1097
  'flat',
@@ -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
  /*!
package/lib/types/map.js CHANGED
@@ -21,7 +21,7 @@ const populateModelSymbol = require('../helpers/symbols').populateModelSymbol;
21
21
  class MongooseMap extends Map {
22
22
  constructor(v, path, doc, schemaType) {
23
23
  if (getConstructorName(v) === 'Object') {
24
- v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []);
24
+ v = Object.keys(v).map(key => [key, v[key]]);
25
25
  }
26
26
  super(v);
27
27
  this.$__parent = doc?.$__ != null ? doc : null;
@@ -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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "9.11.4",
4
+ "version": "9.12.1",
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
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",
@@ -89,6 +88,7 @@
89
88
  "docs:prepare:publish:8x": "env DOCS_DEPLOY=true npm run docs:generate && git checkout gh-pages && rm -rf ./docs/8.x && mv ./tmp ./docs/8.x",
90
89
  "docs:check-links": "linkinator http://127.0.0.1:8089 --silent --recurse --skip cdn.carbonads.com --skip m.servedby-buysellads.com --skip \"127\\.0\\.0\\.1:8089/docs/\\d+.x\"",
91
90
  "docs:update-mongodb-links": "node ./scripts/update-mongodb-links.js",
91
+ "checkLibCharset": "node ./scripts/checkLibCharset.js",
92
92
  "lint": "eslint .",
93
93
  "lint-js": "eslint . --ext .js --ext .cjs",
94
94
  "lint-ts": "eslint . --ext .ts",
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
  }