mongoose 9.12.0 → 9.12.2

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/cast.js CHANGED
@@ -113,6 +113,11 @@ module.exports = function cast(schema, obj, options, context) {
113
113
  } else if (path === '$comment' && !Object.hasOwn(schema.paths, '$comment')) {
114
114
  val = castString(val, path);
115
115
  obj[path] = val;
116
+ } else if (isOperator(path)) {
117
+ // Pass through other top-level operators, like `$jsonSchema`, without casting.
118
+ // MongoDB doesn't allow querying top-level `$` fields, so these can't be paths
119
+ // and `strict` or `strictQuery` shouldn't strip them.
120
+ continue;
116
121
  } else {
117
122
  if (!schema) {
118
123
  // no casting for Mixed types
package/lib/connection.js CHANGED
@@ -755,6 +755,9 @@ Connection.prototype.transaction = function transaction(fn, options) {
755
755
  */
756
756
 
757
757
  async function _wrapUserTransaction(fn, session, mongoose) {
758
+ // `withTransaction()` also retries `fn` when `commitTransaction()` fails with a
759
+ // TransientTransactionError, which the `catch` below does not see. No-op on the first attempt.
760
+ _resetSessionDocuments(session);
758
761
  try {
759
762
  const res = mongoose.transactionAsyncLocalStorage == null
760
763
  ? await fn(session)
@@ -1050,7 +1053,7 @@ Connection.prototype._flushQueue = function _flushQueue() {
1050
1053
  * @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
1051
1054
  * @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.
1052
1055
  * @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.
1053
- * @param {boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
1056
+ * @param {boolean} [options.autoCreate=true] Set to `false` to disable Mongoose automatically calling `createCollection()` on every model created on this connection. Mongoose sets this option to `false` when `readPreference` is `secondary`, `secondaryPreferred`, or `nearest`. Setting `autoCreate: true` with `secondary` or `secondaryPreferred` throws an error.
1054
1057
  * @returns {Promise<Connection>}
1055
1058
  * @api public
1056
1059
  */
@@ -7,6 +7,7 @@
7
7
  const MongooseError = require('../error/mongooseError');
8
8
  const Readable = require('stream').Readable;
9
9
  const eachAsync = require('../helpers/cursor/eachAsync');
10
+ const waitForInitialization = require('../helpers/cursor/waitForInitialization');
10
11
  const immediate = require('../helpers/immediate');
11
12
  const kareem = require('kareem');
12
13
  const util = require('util');
@@ -42,6 +43,7 @@ function AggregationCursor(agg) {
42
43
  Readable.call(this, { autoDestroy: true, objectMode: true });
43
44
 
44
45
  this.cursor = null;
46
+ this._initializationComplete = false;
45
47
  this.agg = agg;
46
48
  this._transforms = [];
47
49
  const connection = agg._connection;
@@ -58,6 +60,7 @@ function AggregationCursor(agg) {
58
60
  options = driverOptions;
59
61
  }
60
62
  this.cursor = connection.db.aggregate(agg._pipeline, options);
63
+ this._initializationComplete = true;
61
64
  setImmediate(() => this.emit('cursor', this.cursor));
62
65
  } else {
63
66
  _init(model, this, agg);
@@ -108,10 +111,15 @@ function _getRawCursor(model, aggregationCursor, agg) {
108
111
  }
109
112
  const cursor = model.collection.aggregate(agg._pipeline, options);
110
113
  aggregationCursor.cursor = cursor;
114
+ aggregationCursor._initializationComplete = true;
111
115
  aggregationCursor.emit('cursor', cursor);
112
116
  } catch (err) {
117
+ aggregationCursor._initializationComplete = true;
113
118
  aggregationCursor._markError(err);
114
- aggregationCursor.listeners('error').length > 0 && aggregationCursor.emit('error', aggregationCursor._error);
119
+ if (aggregationCursor.listeners('error').length > 0) {
120
+ aggregationCursor._errorEmitted = true;
121
+ aggregationCursor.emit('error', aggregationCursor._error);
122
+ }
115
123
  }
116
124
  }
117
125
 
@@ -126,6 +134,7 @@ function _getRawCursor(model, aggregationCursor, agg) {
126
134
  */
127
135
 
128
136
  function _handlePreHookError(queryCursor, err) {
137
+ queryCursor._initializationComplete = true;
129
138
  if (err instanceof kareem.skipWrappedFunction) {
130
139
  const resultValue = err.args[0];
131
140
  if (resultValue != null && (!Array.isArray(resultValue) || resultValue.length)) {
@@ -136,14 +145,20 @@ function _handlePreHookError(queryCursor, err) {
136
145
  '".'
137
146
  );
138
147
  queryCursor._markError(err);
139
- queryCursor.listeners('error').length > 0 && queryCursor.emit('error', err);
148
+ if (queryCursor.listeners('error').length > 0) {
149
+ queryCursor._errorEmitted = true;
150
+ queryCursor.emit('error', err);
151
+ }
140
152
  return;
141
153
  }
142
154
  queryCursor.emit('cursor', null);
143
155
  return;
144
156
  }
145
157
  queryCursor._markError(err);
146
- queryCursor.listeners('error').length > 0 && queryCursor.emit('error', err);
158
+ if (queryCursor.listeners('error').length > 0) {
159
+ queryCursor._errorEmitted = true;
160
+ queryCursor.emit('error', err);
161
+ }
147
162
  }
148
163
 
149
164
 
@@ -159,6 +174,7 @@ AggregationCursor.prototype._read = function() {
159
174
  const _this = this;
160
175
  _next(this, function(error, doc) {
161
176
  if (error) {
177
+ _this._errorEmitted = true;
162
178
  return _this.emit('error', error);
163
179
  }
164
180
  if (!doc) {
@@ -258,7 +274,10 @@ AggregationCursor.prototype.close = async function close() {
258
274
  try {
259
275
  await this.cursor.close();
260
276
  } catch (error) {
261
- this.listeners('error').length > 0 && this.emit('error', error);
277
+ if (this.listeners('error').length > 0) {
278
+ this._errorEmitted = true;
279
+ this.emit('error', error);
280
+ }
262
281
  throw error;
263
282
  }
264
283
  this.emit('close');
@@ -273,21 +292,22 @@ AggregationCursor.prototype.close = async function close() {
273
292
  * @method _destroy
274
293
  */
275
294
 
276
- AggregationCursor.prototype._destroy = function _destroy(_err, callback) {
295
+ AggregationCursor.prototype._destroy = function _destroy(error, callback) {
277
296
  let waitForCursor = null;
278
- if (!this.cursor) {
279
- waitForCursor = new Promise((resolve) => {
280
- this.once('cursor', resolve);
281
- });
297
+ if (!this._initializationComplete) {
298
+ waitForCursor = waitForInitialization(this);
282
299
  } else {
283
300
  waitForCursor = Promise.resolve();
284
301
  }
285
302
 
286
303
  waitForCursor
287
- .then(() => this.cursor.close())
304
+ .then(() => this.cursor?.close())
288
305
  .then(() => {
289
306
  this._closed = true;
290
- callback();
307
+ // Skip errors Mongoose already emitted itself, because Node doesn't know those errors were
308
+ // reported, and skip if there are no error listeners, because Node would throw.
309
+ const shouldEmitError = !this._errorEmitted && this.listeners('error').length > 0;
310
+ callback(shouldEmitError ? error : null);
291
311
  })
292
312
  .catch(error => {
293
313
  callback(error);
@@ -7,6 +7,7 @@
7
7
  const MongooseError = require('../error/mongooseError');
8
8
  const Readable = require('stream').Readable;
9
9
  const eachAsync = require('../helpers/cursor/eachAsync');
10
+ const waitForInitialization = require('../helpers/cursor/waitForInitialization');
10
11
  const helpers = require('../queryHelpers');
11
12
  const kareem = require('kareem');
12
13
  const immediate = require('../helpers/immediate');
@@ -44,6 +45,7 @@ function QueryCursor(query) {
44
45
  Readable.call(this, { autoDestroy: true, objectMode: true });
45
46
 
46
47
  this.cursor = null;
48
+ this._initializationComplete = false;
47
49
  this.skipped = false;
48
50
  this.query = query;
49
51
  this._closed = false;
@@ -56,6 +58,7 @@ function QueryCursor(query) {
56
58
 
57
59
  const onPreComplete = (err) => {
58
60
  if (err != null) {
61
+ this._initializationComplete = true;
59
62
  if (err instanceof kareem.skipWrappedFunction) {
60
63
  const resultValue = err.args[0];
61
64
  if (resultValue != null && (!Array.isArray(resultValue) || resultValue.length)) {
@@ -66,7 +69,10 @@ function QueryCursor(query) {
66
69
  '".'
67
70
  );
68
71
  this._markError(err);
69
- this.listeners('error').length > 0 && this.emit('error', err);
72
+ if (this.listeners('error').length > 0) {
73
+ this._errorEmitted = true;
74
+ this.emit('error', err);
75
+ }
70
76
  return;
71
77
  }
72
78
  this.skipped = true;
@@ -74,7 +80,10 @@ function QueryCursor(query) {
74
80
  return;
75
81
  }
76
82
  this._markError(err);
77
- this.listeners('error').length > 0 && this.emit('error', err);
83
+ if (this.listeners('error').length > 0) {
84
+ this._errorEmitted = true;
85
+ this.emit('error', err);
86
+ }
78
87
  return;
79
88
  }
80
89
  const { middleware, ...options } = query._optionsForExec();
@@ -110,7 +119,8 @@ function QueryCursor(query) {
110
119
  };
111
120
 
112
121
  const preFilter = buildMiddlewareFilter(query.options, 'pre');
113
- model.hooks.execPre('find', query, [], { filter: preFilter }).then(() => onPreComplete(null), err => onPreComplete(err));
122
+ // `onPreComplete(null)` can throw, for example if `_optionsForExec()` fails to cast the projection
123
+ model.hooks.execPre('find', query, [], { filter: preFilter }).then(() => onPreComplete(null)).catch(err => onPreComplete(err));
114
124
  }
115
125
 
116
126
  util.inherits(QueryCursor, Readable);
@@ -123,10 +133,15 @@ function _getRawCursor(query, queryCursor) {
123
133
  try {
124
134
  const cursor = query.model.collection.find(query._conditions, queryCursor.options);
125
135
  queryCursor.cursor = cursor;
136
+ queryCursor._initializationComplete = true;
126
137
  queryCursor.emit('cursor', cursor);
127
138
  } catch (err) {
139
+ queryCursor._initializationComplete = true;
128
140
  queryCursor._markError(err);
129
- queryCursor.listeners('error').length > 0 && queryCursor.emit('error', queryCursor._error);
141
+ if (queryCursor.listeners('error').length > 0) {
142
+ queryCursor._errorEmitted = true;
143
+ queryCursor.emit('error', queryCursor._error);
144
+ }
130
145
  }
131
146
  }
132
147
 
@@ -141,6 +156,7 @@ function _getRawCursor(query, queryCursor) {
141
156
  QueryCursor.prototype._read = function() {
142
157
  _next(this, (error, doc) => {
143
158
  if (error) {
159
+ this._errorEmitted = true;
144
160
  return this.emit('error', error);
145
161
  }
146
162
  if (!doc) {
@@ -255,7 +271,10 @@ QueryCursor.prototype.close = async function close() {
255
271
  this._closed = true;
256
272
  this.emit('close');
257
273
  } catch (error) {
258
- this.listeners('error').length > 0 && this.emit('error', error);
274
+ if (this.listeners('error').length > 0) {
275
+ this._errorEmitted = true;
276
+ this.emit('error', error);
277
+ }
259
278
  throw error;
260
279
  }
261
280
  };
@@ -269,23 +288,24 @@ QueryCursor.prototype.close = async function close() {
269
288
  * @method _destroy
270
289
  */
271
290
 
272
- QueryCursor.prototype._destroy = function _destroy(_err, callback) {
291
+ QueryCursor.prototype._destroy = function _destroy(error, callback) {
273
292
  let waitForCursor = null;
274
- if (!this.cursor) {
275
- waitForCursor = new Promise((resolve) => {
276
- this.once('cursor', resolve);
277
- });
293
+ if (!this._initializationComplete) {
294
+ waitForCursor = waitForInitialization(this);
278
295
  } else {
279
296
  waitForCursor = Promise.resolve();
280
297
  }
281
298
 
282
299
  waitForCursor
283
300
  .then(() => {
284
- return this.cursor.close();
301
+ return this.cursor?.close();
285
302
  })
286
303
  .then(() => {
287
304
  this._closed = true;
288
- callback();
305
+ // Skip errors Mongoose already emitted itself, because Node doesn't know those errors were
306
+ // reported, and skip if there are no error listeners, because Node would throw.
307
+ const shouldEmitError = !this._errorEmitted && this.listeners('error').length > 0;
308
+ callback(shouldEmitError ? error : null);
289
309
  })
290
310
  .catch(error => {
291
311
  callback(error);
package/lib/document.js CHANGED
@@ -1706,8 +1706,11 @@ Document.prototype.$__set = function(pathToMark, path, options, constructing, pa
1706
1706
  let value = isMap ? obj.get(parts[i]) : obj[parts[i]];
1707
1707
  // Skip inherited properties like `Object.prototype.toString`, document methods,
1708
1708
  // or document internals like `$__schema` to avoid setting properties on shared
1709
- // objects. Document properties are getters on the prototype, so check `_doc`.
1710
- if (!isMap && !Object.hasOwn(obj.$__ == null ? obj : obj._doc, parts[i]) && parts[i] in obj) {
1709
+ // objects. Document properties are getters on the prototype, so read raw values
1710
+ // from `_doc`. Nested properties have a `$__` but their `_doc` is their parent's
1711
+ // `_doc`.
1712
+ const raw = obj.$__ != null && !obj.$__isNested ? obj._doc : obj;
1713
+ if (!isMap && !Object.hasOwn(raw, parts[i]) && parts[i] in obj) {
1711
1714
  return;
1712
1715
  }
1713
1716
  if (utils.isPOJO(value)) {
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ module.exports = function waitForInitialization(cursor) {
4
+ return new Promise(resolve => {
5
+ const onInitialized = () => {
6
+ // A casting error can be emitted while cursor creation is still pending.
7
+ if (!cursor._initializationComplete) {
8
+ return;
9
+ }
10
+ cursor.removeListener('cursor', onInitialized);
11
+ cursor.removeListener('error', onInitialized);
12
+ resolve();
13
+ };
14
+ cursor.on('cursor', onInitialized);
15
+ cursor.on('error', onInitialized);
16
+ });
17
+ };
@@ -71,7 +71,7 @@ class PathTrie {
71
71
 
72
72
  /**
73
73
  * Check if `path` or any of its ancestor paths exist in the trie. `path` is
74
- * either a single segment string or a pre-split array of segments — lookups
74
+ * either a single segment string or a pre-split array of segments - lookups
75
75
  * never split, callers are responsible for splitting dotted paths.
76
76
  * For example, with a trie containing 'profile':
77
77
  * matchesPathOrAncestor(['profile', 'firstName']) === true
@@ -89,7 +89,7 @@ class PathTrie {
89
89
  /**
90
90
  * Check if `path`, any of its ancestor paths, or any of its descendant paths
91
91
  * exist in the trie. `path` is either a single segment string or a pre-split
92
- * array of segments — lookups never split, callers are responsible for
92
+ * array of segments - lookups never split, callers are responsible for
93
93
  * splitting dotted paths. For example:
94
94
  * new PathTrie(['profile']).overlapsPath(['profile', 'firstName']) === true
95
95
  * new PathTrie(['profile.firstName']).overlapsPath('profile') === true
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Store the read preference and read concern that the populate options `pops` inherit from
5
+ * `query`'s explicit settings. Schema-level `read` and `readConcern` defaults are not inherited:
6
+ * each populate query applies its own model's schema defaults. `_execPopulateQuery()` applies
7
+ * these unless the populate options set their own.
8
+ *
9
+ * Store them separately from `pop.options` because a query's clones share its populate options:
10
+ * inherited values written to `pop.options` would look like explicit settings to later executions.
11
+ */
12
+
13
+ module.exports = function setInheritedReadOptions(query, pops) {
14
+ const options = query.options;
15
+ const readPreference = 'readPreference' in options ? options.readPreference : undefined;
16
+
17
+ for (const pop of pops) {
18
+ pop._inheritedReadPreference = readPreference;
19
+ pop._inheritedReadConcern = options.readConcern;
20
+ }
21
+ };
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ const PopulateOptions = require('../../options/populateOptions');
4
+ const clone = require('../clone');
5
+ const specialProperties = require('../specialProperties');
6
+
7
+ /*!
8
+ * Deep clone a query's `_mongooseOptions` so a cloned query doesn't share state with the
9
+ * original. `clone()` returns class instances as-is, so explicitly copy `PopulateOptions`,
10
+ * including nested populate: populate options are mutable, and executing a query writes
11
+ * per-execution state like `session` and `lean` into them.
12
+ */
13
+
14
+ module.exports = function cloneMongooseOptions(mongooseOptions) {
15
+ const { populate, ...rest } = mongooseOptions;
16
+ const ret = clone(rest);
17
+ if (populate != null) {
18
+ ret.populate = {};
19
+ for (const path of Object.keys(populate)) {
20
+ if (specialProperties.has(path)) {
21
+ continue;
22
+ }
23
+ ret.populate[path] = clonePopulate(populate[path]);
24
+ }
25
+ }
26
+ return ret;
27
+ };
28
+
29
+ function clonePopulate(pop) {
30
+ if (Array.isArray(pop)) {
31
+ return pop.map(clonePopulate);
32
+ }
33
+ if (pop == null || typeof pop !== 'object') {
34
+ return pop;
35
+ }
36
+
37
+ // Skip `_docs` and `_childDocs`: they hold results of previous executions, see gh-11641
38
+ const { populate, _docs, _childDocs, ...rest } = pop;
39
+ const ret = pop instanceof PopulateOptions ? new PopulateOptions(rest) : clone(rest);
40
+ if (populate !== undefined) {
41
+ ret.populate = clonePopulate(populate);
42
+ }
43
+ return ret;
44
+ }
@@ -24,7 +24,7 @@ module.exports = function sanitizeFilter(filter) {
24
24
  if (key === '$and' || key === '$or' || key === '$nor') {
25
25
  sanitizeFilter(value);
26
26
  continue;
27
- } else if (key === '$jsonSchema' || key === '$where' || key === '$expr' || key === '$text') {
27
+ } else if (key[0] === '$') {
28
28
  throw new MongooseError(key + ' is not allowed with sanitizeFilter');
29
29
  }
30
30
 
@@ -7,7 +7,24 @@ module.exports = function sanitizeProjection(projection) {
7
7
 
8
8
  const keys = Object.keys(projection);
9
9
  for (let i = 0; i < keys.length; ++i) {
10
- if (typeof projection[keys[i]] === 'string') {
10
+ const value = projection[keys[i]];
11
+ if (typeof value === 'string') {
12
+ projection[keys[i]] = 1;
13
+ continue;
14
+ }
15
+ if (value == null || typeof value !== 'object') {
16
+ continue;
17
+ }
18
+ // Only allow `$meta: 'textScore'`, `$elemMatch`, and numeric `$slice`. Nested sub-projections, arrays, and
19
+ // expressions like `{ name: { $concat: ['$password'] } }` become `1`. Note that
20
+ // `{ $slice: ['$otherArray', 1] }` is an expression that can read another field, and
21
+ // `$meta: 'indexKey'` and `$meta: 'sortKey'` can return values of `select: false` paths.
22
+ const slice = value.$slice;
23
+ const isAllowedProjectionOperator = value.$meta === 'textScore' ||
24
+ value.$elemMatch != null ||
25
+ typeof slice === 'number' ||
26
+ (Array.isArray(slice) && slice.every(v => typeof v === 'number'));
27
+ if (!isAllowedProjectionOperator) {
11
28
  projection[keys[i]] = 1;
12
29
  }
13
30
  }
@@ -6,7 +6,9 @@
6
6
  */
7
7
 
8
8
  module.exports = function cleanPositionalOperators(path) {
9
- return path.
10
- replace(/\.\$(\[[^\]]*\])?(?=\.)/g, '.0').
11
- replace(/\.\$(\[[^\]]*\])?$/g, '.0');
9
+ // Most paths have no positional operators, and a single-char search is much cheaper than running the regexp
10
+ if (path.indexOf('$') === -1) {
11
+ return path;
12
+ }
13
+ return path.replace(/\.\$(\[[^\]]*\])?(?=\.|$)/g, '.0');
12
14
  };
@@ -45,7 +45,7 @@ function applyTimestampsToChildren(now, update, schema) {
45
45
 
46
46
  function _applyTimestampToUpdateOperator(op) {
47
47
  for (const key of Object.keys(op)) {
48
- const $path = schema.path(key.replace(/\.\$\./i, '.').replace(/.\$$/, ''));
48
+ const $path = schema.path(cleanPositionalOperators(key));
49
49
  if (op[key] &&
50
50
  $path &&
51
51
  $path.$isMongooseDocumentArray &&
@@ -70,13 +70,24 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
70
70
  continue;
71
71
  }
72
72
 
73
- const firstKey = keys[0];
74
- if (firstKey === '$and' || firstKey === '$or') {
75
- for (const key of keys) {
73
+ // Logical operators may appear anywhere in the filter, before or after field keys,
74
+ // so recurse into each of them and cast the remaining keys as fields.
75
+ const fieldKeys = [];
76
+ for (const key of keys) {
77
+ if (key === '$and' || key === '$or' || key === '$nor') {
76
78
  _castArrayFilters(filter[key], schema, strictQuery, updatedPathsByFilter, query);
79
+ } else if (key.charAt(0) !== '$') {
80
+ // $comment allowed here but we should not cast $comment. MongoDB server 9.x
81
+ // disallows array element identifiers that start with $; `arr.$[$el]` fails
82
+ // with "unknown top level operator".
83
+ fieldKeys.push(key);
77
84
  }
85
+ }
86
+ if (fieldKeys.length === 0) {
78
87
  continue;
79
88
  }
89
+
90
+ const firstKey = fieldKeys[0];
80
91
  const dot = firstKey.indexOf('.');
81
92
  const filterWildcardPath = dot === -1 ? firstKey : firstKey.substring(0, dot);
82
93
  if (updatedPathsByFilter[filterWildcardPath] == null) {
@@ -94,7 +105,7 @@ function _castArrayFilters(arrayFilters, schema, strictQuery, updatedPathsByFilt
94
105
  discriminatorValueMap[baseFilterPath] = filter[filterWildcardPath + '.' + filterBaseSchema.options.discriminatorKey];
95
106
  }
96
107
 
97
- for (const key of keys) {
108
+ for (const key of fieldKeys) {
98
109
  if (updatedPathsByFilter[key] === null) {
99
110
  continue;
100
111
  }
@@ -4,7 +4,6 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
- const ValidationError = require('../error/validation');
8
7
  const cleanPositionalOperators = require('./schema/cleanPositionalOperators');
9
8
  const flatten = require('./common').flatten;
10
9
 
@@ -81,7 +80,7 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
81
80
  const validatorsToExecute = [];
82
81
  const validationErrors = [];
83
82
 
84
- const alreadyValidated = [];
83
+ let alreadyValidated = null;
85
84
 
86
85
  const context = query;
87
86
  for (let i = 0; i < numUpdates; ++i) {
@@ -93,6 +92,9 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
93
92
  if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) {
94
93
  continue;
95
94
  }
95
+ if (isPull[updates[i]] && schemaPath.$isMongooseArray) {
96
+ continue;
97
+ }
96
98
 
97
99
  if (v && Array.isArray(v.$in)) {
98
100
  v.$in.forEach((v, i) => {
@@ -104,13 +106,13 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
104
106
  );
105
107
  });
106
108
  } else {
107
- if (isPull[updates[i]] &&
108
- schemaPath.$isMongooseArray) {
109
+ if (alreadyValidated != null && hasValidatedAncestor(alreadyValidated, updates[i])) {
109
110
  continue;
110
111
  }
111
112
 
112
113
  if (schemaPath.$isMongooseDocumentArrayElement && v?.$__ != null) {
113
- alreadyValidated.push(updates[i]);
114
+ alreadyValidated ??= new Set();
115
+ alreadyValidated.add(updates[i]);
114
116
  validatorsToExecute.push(
115
117
  schemaPath.doValidate(v, context, { updateValidator: true }).catch(err => {
116
118
  if (err.errors) {
@@ -126,21 +128,12 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
126
128
  })
127
129
  );
128
130
  } else {
129
- const isAlreadyValidated = alreadyValidated.find(path => updates[i].startsWith(path + '.'));
130
- if (isAlreadyValidated) {
131
- continue;
132
- }
133
131
  if (schemaPath.$isSingleNested) {
134
- alreadyValidated.push(updates[i]);
132
+ alreadyValidated ??= new Set();
133
+ alreadyValidated.add(updates[i]);
135
134
  }
136
135
  validatorsToExecute.push(
137
136
  schemaPath.doValidate(v, context, { updateValidator: true }).catch(err => {
138
- if (schemaPath.schema != null &&
139
- schemaPath.schema.options.storeSubdocValidationError === false &&
140
- err instanceof ValidationError) {
141
- return;
142
- }
143
-
144
137
  if (err) {
145
138
  err.path = updates[i];
146
139
  validationErrors.push(err);
@@ -184,3 +177,18 @@ module.exports = async function updateValidators(query, schema, castedDoc, optio
184
177
  await Promise.all(validatorsToExecute);
185
178
  return validationErrors;
186
179
  };
180
+
181
+ /*!
182
+ * Returns true if `path` is underneath a path in `alreadyValidated`. Checks each
183
+ * ancestor of `path` with a Set lookup, so the cost depends on the depth of `path`
184
+ * rather than on the number of subdocuments validated so far.
185
+ */
186
+
187
+ function hasValidatedAncestor(alreadyValidated, path) {
188
+ for (let i = path.indexOf('.'); i !== -1; i = path.indexOf('.', i + 1)) {
189
+ if (alreadyValidated.has(path.slice(0, i))) {
190
+ return true;
191
+ }
192
+ }
193
+ return false;
194
+ }
package/lib/model.js CHANGED
@@ -72,6 +72,7 @@ const prepareDiscriminatorPipeline = require('./helpers/aggregate/prepareDiscrim
72
72
  const pushNestedArrayPaths = require('./helpers/model/pushNestedArrayPaths');
73
73
  const removeDeselectedForeignField = require('./helpers/populate/removeDeselectedForeignField');
74
74
  const setDottedPath = require('./helpers/path/setDottedPath');
75
+ const setInheritedReadOptions = require('./helpers/populate/setInheritedReadOptions');
75
76
  const splitPopulateQuery = require('./helpers/populate/splitPopulateQuery');
76
77
  const { buildMiddlewareFilter } = require('./helpers/buildMiddlewareFilter');
77
78
  const util = require('util');
@@ -1928,7 +1929,7 @@ Model.discriminators;
1928
1929
  * #### Example:
1929
1930
  *
1930
1931
  * await Character.find(Character.translateAliases({
1931
- * '名': 'Eddard Stark' // Alias for 'name'
1932
+ * nombre: 'Eddard Stark' // Alias for 'name'
1932
1933
  * });
1933
1934
  *
1934
1935
  * By default, `translateAliases()` overwrites raw fields with aliased fields.
@@ -3058,7 +3059,7 @@ Model.startSession = function() {
3058
3059
  * @param {boolean} [options.ordered=true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`.
3059
3060
  * @param {boolean} [options.rawResult=false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/7.0/interfaces/InsertManyResult.html) with a `mongoose` property that contains `validationErrors` and `results` if this is an unordered `insertMany`.
3060
3061
  * @param {boolean} [options.lean=false] if `true`, skips hydrating the documents. This means Mongoose will **not** cast, validate, or apply defaults to any of the documents passed to `insertMany()`. This option is useful if you need the extra performance, but comes with data integrity risk. Consider using with [`castObject()`](https://mongoosejs.com/docs/api/model.html#Model.castObject()) and [`applyDefaults()`](https://mongoosejs.com/docs/api/model.html#Model.applyDefaults()).
3061
- * @param {number} [options.limit=null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.
3062
+ * @param {number} [options.limit=1000] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.
3062
3063
  * @param {string|object|Array} [options.populate=null] populates the result documents. This option is a no-op if `rawResult` is set.
3063
3064
  * @param {boolean} [options.throwOnValidationError=false] If true and `ordered: false`, throw an error if one of the operations failed validation, but all valid operations completed successfully.
3064
3065
  * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
@@ -4395,7 +4396,7 @@ Model.validate = async function validate(obj, pathsOrOptions, context) {
4395
4396
  const pieces = p.split('.');
4396
4397
  let cur = pieces[0];
4397
4398
 
4398
- for (const piece of pieces) {
4399
+ for (const piece of pieces.slice(1)) {
4399
4400
  if (_pathsToValidate.has(cur)) {
4400
4401
  return true;
4401
4402
  }
@@ -4824,6 +4825,13 @@ function _execPopulateQuery(mod, match, select) {
4824
4825
  queryOptions.perDocumentLimit = mod.options.perDocumentLimit;
4825
4826
  }
4826
4827
  Object.assign(queryOptions, mod.options.options);
4828
+ // Inherit the parent query's read settings unless populate options set them, see `setInheritedReadOptions()`
4829
+ if (queryOptions.readPreference == null && mod.options._inheritedReadPreference != null) {
4830
+ queryOptions.readPreference = mod.options._inheritedReadPreference;
4831
+ }
4832
+ if (queryOptions.readConcern == null && mod.options._inheritedReadConcern != null) {
4833
+ queryOptions.readConcern = mod.options._inheritedReadConcern;
4834
+ }
4827
4835
 
4828
4836
  if (mod.count) {
4829
4837
  delete queryOptions.skip;
@@ -4918,6 +4926,9 @@ function _execPopulateQuery(mod, match, select) {
4918
4926
  delete query._deferredPopulate;
4919
4927
  }
4920
4928
  if (shouldDeferSubPopulate) {
4929
+ // Deferred sub-populate skips `preparePopulationOptionsMQ()`, so inherit read settings here
4930
+ subPopulate = utils.populate(subPopulate);
4931
+ setInheritedReadOptions(query, subPopulate);
4921
4932
  deferredPopulates.push(subPopulate);
4922
4933
  }
4923
4934
  return { docs, deferredPopulates };
package/lib/mongoose.js CHANGED
@@ -221,25 +221,32 @@ Mongoose.prototype.setDriver = function setDriver(driver) {
221
221
  *
222
222
  * Currently supported options are:
223
223
  * - `allowDiskUse`: Set to `true` to set `allowDiskUse` to true to all aggregation operations by default.
224
- * - `applyPluginsToChildSchemas`: `true` by default. Set to false to skip applying global plugins to child schemas
225
- * - `applyPluginsToDiscriminators`: `false` by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
226
- * - `autoCreate`: Set to `true` to make Mongoose call [`Model.createCollection()`](https://mongoosejs.com/docs/api/model.html#Model.createCollection()) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist.
227
- * - `autoIndex`: `true` by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.
224
+ * - `applyPluginsToChildSchemas`: `true` by default. Set to `false` to skip applying global plugins to child schemas
225
+ * - `applyPluginsToDiscriminators`: `false` by default. Set to `true` to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
226
+ * - `autoCreate`: `true` by default. Mongoose calls [`Model.createCollection()`](https://mongoosejs.com/docs/api/model.html#Model.createCollection()) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist. Set to `false` to disable this behavior. Connections with `readPreference` set to `secondary`, `secondaryPreferred`, or `nearest` disable `autoCreate`.
227
+ * - `autoIndex`: `true` by default. Set to `false` to disable automatic index creation for all models associated with this Mongoose instance.
228
+ * - `autoSearchIndex`: `false` by default. Set to `true` to automatically create [Atlas search indexes](https://mongoosejs.com/docs/guide.html#autoSearchIndex) defined in your schemas.
228
229
  * - `bufferCommands`: enable/disable mongoose's buffering mechanism for all connections and models
229
230
  * - `bufferTimeoutMS`: If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds).
230
231
  * - `cloneSchemas`: `false` by default. Set to `true` to `clone()` all schemas before compiling into a model.
232
+ * - `createInitialConnection`: `true` by default. Set to `false` to disable the creation of the initial default connection. If the default connection already exists, Mongoose removes it only if it is disconnected and has no models.
231
233
  * - `debug`: If `true`, prints the operations mongoose sends to MongoDB to the console. If an object is passed, you can set `color`, `shell`, and `timestamp` options. If `timestamp` is `true`, Mongoose prefixes console debug output with an ISO timestamp in brackets. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arguments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`.
234
+ * - `forceRepopulate`: `true` by default. Set to `false` to prevent `populate()` from repopulating paths that are already populated.
232
235
  * - `id`: If `true`, adds a `id` virtual to all schemas unless overwritten on a per-schema basis.
233
236
  * - `maxTimeMS`: If set, attaches [maxTimeMS](https://www.mongodb.com/docs/manual/reference/operator/meta/maxTimeMS/) to every query
234
- * - `objectIdGetter`: `true` by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter.
237
+ * - `objectIdGetter`: `true` by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to `false` to remove the getter.
235
238
  * - `overwriteModels`: Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`.
236
239
  * - `returnDocument`: Set to `'before'` or `'after'` to set the default value for the `returnDocument` option to `findOneAndUpdate()`, `findByIdAndUpdate()`, and `findOneAndReplace()`. Defaults to `'before'`, which returns the document before the update was applied. Read our [`findOneAndUpdate()` tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html) for more information.
237
240
  * - `returnOriginal`: **Deprecated.** Use `returnDocument` instead. If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](https://mongoosejs.com/docs/tutorials/findoneandupdate.html) for more information.
238
- * - `runValidators`: `false` by default. Set to true to enable [update validators](https://mongoosejs.com/docs/validation.html#update-validators) for all validators by default.
239
- * - `sanitizeFilter`: `false` by default. Set to true to enable the [sanitization of the query filters](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.sanitizeFilter()) against query selector injection attacks by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`.
240
- * - `selectPopulatedPaths`: `true` by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
241
+ * - `runValidators`: `false` by default. Set to `true` to enable [update validators](https://mongoosejs.com/docs/validation.html#update-validators) for all validators by default.
242
+ * - `sanitizeFilter`: `false` by default. Set to `true` to enable the [sanitization of the query filters](https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.sanitizeFilter()) against query selector injection attacks by wrapping any nested objects that have a property whose name starts with `$` in a `$eq`.
243
+ * - `sanitizeProjection`: `false` by default. Set to `true` to enable [`sanitizeProjection`](https://mongoosejs.com/docs/api/query.html#Query.prototype.sanitizeProjection()) on all queries.
244
+ * - `selectPopulatedPaths`: `true` by default. Set to `false` to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
245
+ * - `setDefaultsOnInsert`: `true` by default. Set to `false` to stop Mongoose from applying schema defaults when an update creates a new document with `upsert`.
246
+ * - `strictPopulate`: `true` by default. Set to `false` to allow populating paths that aren't in the schema.
241
247
  * - `strictQuery`: `false` by default. May be `false`, `true`, or `'throw'`. Sets the default [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery) mode for schemas.
242
248
  * - `strict`: `true` by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
249
+ * - `strictRead`: `false` by default. May be `false`, `true`, or `'throw'`. Sets the default [strictRead](https://mongoosejs.com/docs/guide.html#strictRead) mode for schemas.
243
250
  * - `timestamps.createdAt.immutable`: `true` by default. If `false`, it will change the `createdAt` field to be [`immutable: false`](https://mongoosejs.com/docs/api/schematype.html#SchemaType.prototype.immutable()) which means you can update the `createdAt`
244
251
  * - `toJSON`: `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](https://mongoosejs.com/docs/api/document.html#Document.prototype.toJSON()), for determining how Mongoose documents get serialized by `JSON.stringify()`
245
252
  * - `toObject`: `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject())
@@ -455,7 +462,7 @@ Mongoose.prototype.createConnection = function createConnection(uri, options) {
455
462
  * @param {boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
456
463
  * @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.
457
464
  * @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.
458
- * @param {boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
465
+ * @param {boolean} [options.autoCreate=true] Set to `false` to disable Mongoose automatically calling `createCollection()` on every model created on this connection. Mongoose sets this option to `false` when `readPreference` is `secondary`, `secondaryPreferred`, or `nearest`. Setting `autoCreate: true` with `secondary` or `secondaryPreferred` throws an error.
459
466
  * @see Mongoose#createConnection https://mongoosejs.com/docs/api/mongoose.html#Mongoose.prototype.createConnection()
460
467
  * @api public
461
468
  * @return {Promise} resolves to `this` if connection succeeded
package/lib/query.js CHANGED
@@ -20,6 +20,7 @@ const castArrayFilters = require('./helpers/update/castArrayFilters');
20
20
  const castNumber = require('./cast/number');
21
21
  const castUpdate = require('./helpers/query/castUpdate');
22
22
  const clone = require('./helpers/clone');
23
+ const cloneMongooseOptions = require('./helpers/query/cloneMongooseOptions');
23
24
  const decorateUpdateWithVersionKey = require('./helpers/update/decorateUpdateWithVersionKey');
24
25
  const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue');
25
26
  const helpers = require('./queryHelpers');
@@ -168,23 +169,31 @@ function Query(conditions, options, model, collection) {
168
169
  }
169
170
  }
170
171
 
171
- // Helper function to check if an object is empty or contains only empty objects/arrays
172
+ // Returns true if `obj` matches every document: every key is a no-op like `$comment`
173
+ // or `$alwaysTrue`, or a `$and` / `$or` that matches every document.
172
174
  function isEmptyFilter(obj) {
173
175
  if (obj == null) return true;
174
176
  if (typeof obj !== 'object') return true;
175
- if (utils.hasOwnKeys(obj) === false) return true;
176
-
177
- // Check $and, $or, $nor arrays
178
- for (const key of ['$and', '$or', '$nor']) {
179
- if (Array.isArray(obj[key])) {
180
- // If array is empty or all elements are empty objects, consider it empty
181
- if (obj[key].length === 0 || obj[key].every(item => isEmptyFilter(item))) {
182
- return true;
183
- }
177
+
178
+ for (const key of Object.keys(obj)) {
179
+ const val = obj[key];
180
+ if (key === '$comment' || key === '$alwaysTrue') {
181
+ continue;
182
+ }
183
+ if (!Array.isArray(val)) {
184
+ return false;
185
+ }
186
+ // `$nor: [{}]` matches no documents, but treat it as empty for backwards compatibility
187
+ if ((key === '$and' || key === '$nor') && val.every(isEmptyFilter)) {
188
+ continue;
189
+ }
190
+ if (key === '$or' && (val.length === 0 || val.some(isEmptyFilter))) {
191
+ continue;
184
192
  }
193
+ return false;
185
194
  }
186
195
 
187
- return false;
196
+ return true;
188
197
  }
189
198
 
190
199
  // Helper function to check for empty/invalid filter
@@ -274,7 +283,7 @@ Query.prototype.toConstructor = function toConstructor() {
274
283
  if (!(this instanceof CustomQuery)) {
275
284
  return new CustomQuery(criteria, options);
276
285
  }
277
- this._mongooseOptions = clone(p._mongooseOptions);
286
+ this._mongooseOptions = cloneMongooseOptions(p._mongooseOptions);
278
287
  Query.call(this, criteria, options || null, model, coll);
279
288
  };
280
289
 
@@ -304,7 +313,7 @@ Query.prototype.toConstructor = function toConstructor() {
304
313
  p._path = this._path;
305
314
  p._distinct = this._distinct;
306
315
  p._collection = this._collection;
307
- p._mongooseOptions = this._mongooseOptions;
316
+ p._mongooseOptions = cloneMongooseOptions(this._mongooseOptions);
308
317
 
309
318
  return CustomQuery;
310
319
  };
@@ -352,7 +361,7 @@ Query.prototype.clone = function() {
352
361
  q._path = this._path;
353
362
  q._distinct = this._distinct;
354
363
  q._collection = this._collection;
355
- q._mongooseOptions = this._mongooseOptions;
364
+ q._mongooseOptions = cloneMongooseOptions(this._mongooseOptions);
356
365
 
357
366
  return q;
358
367
  };
@@ -1138,6 +1147,11 @@ Query.prototype.select = function select() {
1138
1147
  }
1139
1148
  arg = parseProjection(arg, true); // we want to keep the minus and pluses, so add boolean arg.
1140
1149
  if (utils.isObject(arg)) {
1150
+ // `fields['__proto__'] = value` would re-point the projection's prototype
1151
+ if (Object.hasOwn(arg, '__proto__')) {
1152
+ arg = { ...arg };
1153
+ delete arg['__proto__'];
1154
+ }
1141
1155
  if (this.selectedInclusively()) {
1142
1156
  Object.entries(arg).forEach(([key, value]) => {
1143
1157
  if (value) {
@@ -2154,29 +2168,6 @@ Query.prototype._optionsForExec = function(model) {
2154
2168
  }
2155
2169
  }
2156
2170
 
2157
- if (this._mongooseOptions.populate) {
2158
- if (options.readPreference) {
2159
- for (const pop of Object.values(this._mongooseOptions.populate)) {
2160
- if (pop.options?.readPreference === undefined) {
2161
- if (!pop.options) {
2162
- pop.options = {};
2163
- }
2164
- pop.options.readPreference = options.readPreference;
2165
- }
2166
- }
2167
- }
2168
- if (options.readConcern) {
2169
- for (const pop of Object.values(this._mongooseOptions.populate)) {
2170
- if (pop.options?.readConcern === undefined) {
2171
- if (!pop.options) {
2172
- pop.options = {};
2173
- }
2174
- pop.options.readConcern = options.readConcern;
2175
- }
2176
- }
2177
- }
2178
- }
2179
-
2180
2171
  return options;
2181
2172
  };
2182
2173
 
@@ -4320,15 +4311,34 @@ Query.prototype._replaceOne = async function _replaceOne() {
4320
4311
  }
4321
4312
 
4322
4313
  const options = this._optionsForExec(this.model);
4323
- this[queryUpdateSymbol] = new this.model(this[queryUpdateSymbol], null, { skipId: true });
4324
- removeUnusedArrayFilters(this[queryUpdateSymbol], options);
4325
-
4326
- if (_getOption(this, 'runValidators', false)) {
4327
- await this.validate(this[queryUpdateSymbol], options, true);
4314
+ const modelOpts = { skipId: true };
4315
+ if ('strict' in this._mongooseOptions) {
4316
+ modelOpts.strict = this._mongooseOptions.strict;
4328
4317
  }
4329
4318
 
4330
- if (typeof this[queryUpdateSymbol].toBSON === 'function') {
4331
- this[queryUpdateSymbol] = this[queryUpdateSymbol].toBSON();
4319
+ const runValidators = _getOption(this, 'runValidators', false);
4320
+
4321
+ try {
4322
+ this[queryUpdateSymbol] = new this.model(this[queryUpdateSymbol], null, modelOpts);
4323
+
4324
+ removeUnusedArrayFilters(this[queryUpdateSymbol], options);
4325
+
4326
+ if (runValidators) {
4327
+ await this.validate(this[queryUpdateSymbol], options, true);
4328
+ } else if (this[queryUpdateSymbol].$__.validationError) {
4329
+ throw this[queryUpdateSymbol].$__.validationError;
4330
+ }
4331
+
4332
+ if (typeof this[queryUpdateSymbol].toBSON === 'function') {
4333
+ this[queryUpdateSymbol] = this[queryUpdateSymbol].toBSON();
4334
+ }
4335
+ } catch (err) {
4336
+ if (err instanceof ValidationError) {
4337
+ throw err;
4338
+ }
4339
+ const validationError = new ValidationError();
4340
+ validationError.errors[err.path] = err;
4341
+ throw validationError;
4332
4342
  }
4333
4343
 
4334
4344
  return this.mongooseCollection.replaceOne(this._conditions, this[queryUpdateSymbol], options);
@@ -5279,11 +5289,7 @@ Query.prototype._castFields = function _castFields(fields) {
5279
5289
 
5280
5290
  if (selected) {
5281
5291
  // they passed $elemMatch, cast em
5282
- try {
5283
- out = this.cast(this.model, selected);
5284
- } catch (err) {
5285
- return err;
5286
- }
5292
+ out = this.cast(this.model, selected);
5287
5293
 
5288
5294
  // apply the casted field args
5289
5295
  for (let i = 0; i < elemMatchKeys.length; ++i) {
@@ -5306,19 +5312,30 @@ Query.prototype._applyPaths = function applyPaths() {
5306
5312
  }
5307
5313
  this._fields = this._fields || {};
5308
5314
 
5309
- let sanitizeProjection = undefined;
5315
+ let shouldSanitizeProjection = undefined;
5310
5316
  if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5311
- sanitizeProjection = this.model.db.options.sanitizeProjection;
5317
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5312
5318
  } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5313
- sanitizeProjection = this.model.base.options.sanitizeProjection;
5319
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5314
5320
  } else {
5315
- sanitizeProjection = this._mongooseOptions.sanitizeProjection;
5321
+ shouldSanitizeProjection = this._mongooseOptions.sanitizeProjection;
5322
+ }
5323
+
5324
+ // Even with `schemaLevelProjections` disabled, `sanitizeProjection` should strip expressions
5325
+ if (shouldSanitizeProjection) {
5326
+ sanitizeProjection(this._fields);
5316
5327
  }
5317
5328
 
5318
5329
  const schemaLevelProjections = this._mongooseOptions.schemaLevelProjections ?? true;
5319
5330
 
5320
5331
  if (schemaLevelProjections) {
5321
- helpers.applyPaths(this._fields, this.model.schema, sanitizeProjection);
5332
+ // If the filter has a discriminator key, apply that discriminator's schema-level projections
5333
+ let schema = this.model.schema;
5334
+ const discriminatorKey = schema.options.discriminatorKey;
5335
+ if (this._conditions != null && Object.hasOwn(this._conditions, discriminatorKey)) {
5336
+ schema = getDiscriminatorByValue(this.model.discriminators, this._conditions[discriminatorKey])?.schema ?? schema;
5337
+ }
5338
+ helpers.applyPaths(this._fields, schema, shouldSanitizeProjection);
5322
5339
  }
5323
5340
 
5324
5341
  let _selectPopulatedPaths = true;
@@ -12,8 +12,11 @@ const get = require('./helpers/get');
12
12
  const getDiscriminatorByValue =
13
13
  require('./helpers/discriminator/getDiscriminatorByValue');
14
14
  const isDefiningProjection = require('./helpers/projection/isDefiningProjection');
15
+ const isExclusive = require('./helpers/projection/isExclusive');
16
+ const isPOJO = require('./helpers/isPOJO');
15
17
  const clone = require('./helpers/clone');
16
18
  const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive');
19
+ const setInheritedReadOptions = require('./helpers/populate/setInheritedReadOptions');
17
20
 
18
21
  /**
19
22
  * Prepare a set of path options for query population. This is the MongooseQuery
@@ -61,6 +64,7 @@ exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query,
61
64
  pop[i]._localModel = query.model;
62
65
  }
63
66
  }
67
+ setInheritedReadOptions(query, pop);
64
68
 
65
69
  return pop;
66
70
  };
@@ -143,6 +147,16 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
143
147
  const minusPathsToSkip = new Set();
144
148
 
145
149
  if (fields) {
150
+ // `+path` can't override schema-level `select: false` with `sanitizeProjection`. Also remove
151
+ // `-+path`, because collapsing minus paths below would turn it into `+path`.
152
+ if (sanitizeProjection) {
153
+ for (const key of Object.keys(fields)) {
154
+ if (key[0] === '+' || key.startsWith('-+')) {
155
+ delete fields[key];
156
+ }
157
+ }
158
+ }
159
+
146
160
  keys = Object.keys(fields);
147
161
 
148
162
  // Collapse minus paths
@@ -162,6 +176,7 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
162
176
  }
163
177
 
164
178
  keys = Object.keys(fields);
179
+ let hasElemMatch = false;
165
180
  for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) {
166
181
  if (keys[keyIndex][0] === '+') {
167
182
  continue;
@@ -171,15 +186,32 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
171
186
  if (!isDefiningProjection(field)) {
172
187
  continue;
173
188
  }
189
+ // `$elemMatch` is inclusive on its own, but MongoDB treats `{ arr: { $elemMatch }, name: 0 }` as exclusive
190
+ if (field?.$elemMatch != null) {
191
+ hasElemMatch = true;
192
+ continue;
193
+ }
174
194
  if (keys[keyIndex] === '_id' && keys.length > 1) {
175
195
  continue;
176
196
  }
177
197
  if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) {
178
198
  continue;
179
199
  }
200
+ // Nested sub-projections like `{ profile: { bio: 0 } }` are exclusive or inclusive based on their
201
+ // nested values, unlike expressions like `{ $concat: [...] }`, which are always inclusive
202
+ if (isPOJO(field) && !Object.keys(field).some(key => key.startsWith('$'))) {
203
+ exclude = isExclusive(field) ?? undefined;
204
+ if (exclude === undefined) {
205
+ continue;
206
+ }
207
+ break;
208
+ }
180
209
  exclude = !field;
181
210
  break;
182
211
  }
212
+ if (exclude === undefined && hasElemMatch) {
213
+ exclude = false;
214
+ }
183
215
 
184
216
  // Potentially add back minus paths based on schema-level path config
185
217
  // and whether the projection is inclusive
@@ -212,6 +244,13 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
212
244
  if (schema._hasSelectedPaths !== false) {
213
245
  analyzeSchema(schema);
214
246
  }
247
+ // If `sanitizeProjection` removed every inclusion, the projection is now exclusive
248
+ if (sanitizeProjection && exclude === false) {
249
+ const keys = Object.keys(fields);
250
+ if (!keys.some(key => (key !== '_id' || keys.length === 1) && isDefiningProjection(fields[key]) && fields[key])) {
251
+ exclude = true;
252
+ }
253
+ }
215
254
  switch (exclude) {
216
255
  case true:
217
256
  for (const fieldName of excluded) {
@@ -279,7 +318,10 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
279
318
  if (type.$isSchemaMap || path.endsWith('.$*')) {
280
319
  const plusPath = '+' + path;
281
320
  const hasPlusPath = fields && plusPath in fields;
282
- if (type.options?.select === false && !hasPlusPath) {
321
+ if (type.options?.select === false && sanitizeProjection) {
322
+ removeInclusions(path);
323
+ excluded.push(path);
324
+ } else if (type.options?.select === false && !hasPlusPath) {
283
325
  excluded.push(path);
284
326
  }
285
327
  return;
@@ -319,12 +361,11 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
319
361
  return;
320
362
  }
321
363
 
322
- // User overwriting default exclusion
323
- if (type.selected === false && fields[path]) {
324
- if (sanitizeProjection) {
325
- fields[path] = 0;
326
- }
327
-
364
+ if (type.selected === false && sanitizeProjection) {
365
+ // Fall through so `path` is excluded
366
+ removeInclusions(path);
367
+ } else if (type.selected === false && fields[path]) {
368
+ // User overwriting default exclusion
328
369
  return;
329
370
  }
330
371
 
@@ -349,10 +390,8 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
349
390
 
350
391
  // if there are other fields being included, add this one
351
392
  // if no other included fields, leave this out (implied inclusion)
352
- if (exclude === false && keys.length > 1 && !~keys.indexOf(path) && !sanitizeProjection) {
393
+ if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
353
394
  fields[path] = 1;
354
- } else if (exclude == null && sanitizeProjection && type.selected === false) {
355
- fields[path] = 0;
356
395
  }
357
396
 
358
397
  return;
@@ -386,6 +425,21 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
386
425
  return path;
387
426
  }
388
427
 
428
+ // With `sanitizeProjection`, remove anything other than an exclusion that would project in
429
+ // `path`: `path` itself, a parent like `profile` for `profile.ssn`, or a child path.
430
+ function removeInclusions(path) {
431
+ for (const key of Object.keys(fields)) {
432
+ if (isDefiningProjection(fields[key]) && !fields[key]) {
433
+ continue;
434
+ }
435
+ // Positional projections like `comments.$` project in the whole array element
436
+ const keyPath = key.endsWith('.$') ? key.slice(0, -2) : key;
437
+ if (keyPath === path || keyPath.startsWith(path + '.') || path.startsWith(keyPath + '.')) {
438
+ delete fields[key];
439
+ }
440
+ }
441
+ }
442
+
389
443
  function hasExcludedAncestor(fields, path) {
390
444
  let i = -1;
391
445
  while ((i = path.indexOf('.', i + 1)) !== -1) {
@@ -466,18 +466,19 @@ const methods = {
466
466
 
467
467
  rawValues.forEach(function(v) {
468
468
  let found;
469
- const val = +v;
470
469
  switch (type) {
471
470
  case 'doc':
472
471
  found = this.some(function(doc) {
473
472
  return doc.equals(v);
474
473
  });
475
474
  break;
476
- case 'date':
475
+ case 'date': {
476
+ const val = +v;
477
477
  found = this.some(function(d) {
478
478
  return +d === val;
479
479
  });
480
480
  break;
481
+ }
481
482
  case 'ObjectId':
482
483
  found = this.find(o => o.toString() === v.toString());
483
484
  break;
@@ -743,8 +744,7 @@ const methods = {
743
744
  if (isOverwrite) {
744
745
  atomic.$each = values;
745
746
 
746
- if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
747
- atomics.$push.$position != atomic.$position) {
747
+ if (_cannotMergePush(atomics.$push, atomic)) {
748
748
  if (atomic.$position != null) {
749
749
  [].splice.apply(arr, [atomic.$position, 0].concat(values));
750
750
  ret = arr.length;
@@ -762,9 +762,13 @@ const methods = {
762
762
  } else {
763
763
  atomic = values;
764
764
  ret = _basePush.apply(arr, values);
765
+ if (atomics.$push?.$position != null) {
766
+ this._registerAtomic('$set', this);
767
+ }
765
768
  }
766
769
 
767
- this._registerAtomic('$push', atomic);
770
+ // add to a pending `$each` instead of replacing it (gh-16618)
771
+ this._registerAtomic('$push', atomics.$push?.$each?.length ? values : atomic);
768
772
 
769
773
  return ret;
770
774
  },
@@ -1077,6 +1081,18 @@ function _depopulateIfNecessary(arr, docs) {
1077
1081
  }
1078
1082
  }
1079
1083
 
1084
+ /*!
1085
+ * A `{ $each }` push can only join a pending `$push` when neither has
1086
+ * `$position`, `$slice` or `$sort` (gh-14244, gh-16618)
1087
+ */
1088
+
1089
+ function _cannotMergePush(pending, atomic) {
1090
+ if (!pending?.$each?.length) {
1091
+ return false;
1092
+ }
1093
+ return [pending, atomic].some(push => push.$position != null || push.$slice != null || push.$sort != null);
1094
+ }
1095
+
1080
1096
  const returnVanillaArrayMethods = [
1081
1097
  'filter',
1082
1098
  'flat',
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;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "9.12.0",
4
+ "version": "9.12.2",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -88,6 +88,7 @@
88
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",
89
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\"",
90
90
  "docs:update-mongodb-links": "node ./scripts/update-mongodb-links.js",
91
+ "checkLibCharset": "node ./scripts/checkLibCharset.js",
91
92
  "lint": "eslint .",
92
93
  "lint-js": "eslint . --ext .js --ext .cjs",
93
94
  "lint-ts": "eslint . --ext .ts",
@@ -40,6 +40,14 @@ declare module 'mongoose' {
40
40
  */
41
41
  autoIndex?: boolean;
42
42
 
43
+ /**
44
+ * Set to `true` to automatically create [Atlas search indexes](https://mongoosejs.com/docs/guide.html#autoSearchIndex)
45
+ * defined in your schemas.
46
+ *
47
+ * @default false
48
+ */
49
+ autoSearchIndex?: boolean;
50
+
43
51
  /**
44
52
  * enable/disable mongoose's buffering mechanism for all connections and models.
45
53
  *
@@ -86,6 +94,13 @@ declare module 'mongoose' {
86
94
  | stream.Writable
87
95
  | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void);
88
96
 
97
+ /**
98
+ * Set to `false` to prevent `populate()` from repopulating paths that are already populated.
99
+ *
100
+ * @default true
101
+ */
102
+ forceRepopulate?: boolean;
103
+
89
104
  /**
90
105
  * If `true`, adds a `id` virtual to all schemas unless overwritten on a per-schema basis.
91
106
  * @defaultValue true