mongoose 9.12.1 → 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
  */
@@ -116,7 +116,10 @@ function _getRawCursor(model, aggregationCursor, agg) {
116
116
  } catch (err) {
117
117
  aggregationCursor._initializationComplete = true;
118
118
  aggregationCursor._markError(err);
119
- 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
+ }
120
123
  }
121
124
  }
122
125
 
@@ -142,14 +145,20 @@ function _handlePreHookError(queryCursor, err) {
142
145
  '".'
143
146
  );
144
147
  queryCursor._markError(err);
145
- 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
+ }
146
152
  return;
147
153
  }
148
154
  queryCursor.emit('cursor', null);
149
155
  return;
150
156
  }
151
157
  queryCursor._markError(err);
152
- 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
+ }
153
162
  }
154
163
 
155
164
 
@@ -165,6 +174,7 @@ AggregationCursor.prototype._read = function() {
165
174
  const _this = this;
166
175
  _next(this, function(error, doc) {
167
176
  if (error) {
177
+ _this._errorEmitted = true;
168
178
  return _this.emit('error', error);
169
179
  }
170
180
  if (!doc) {
@@ -264,7 +274,10 @@ AggregationCursor.prototype.close = async function close() {
264
274
  try {
265
275
  await this.cursor.close();
266
276
  } catch (error) {
267
- 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
+ }
268
281
  throw error;
269
282
  }
270
283
  this.emit('close');
@@ -279,7 +292,7 @@ AggregationCursor.prototype.close = async function close() {
279
292
  * @method _destroy
280
293
  */
281
294
 
282
- AggregationCursor.prototype._destroy = function _destroy(_err, callback) {
295
+ AggregationCursor.prototype._destroy = function _destroy(error, callback) {
283
296
  let waitForCursor = null;
284
297
  if (!this._initializationComplete) {
285
298
  waitForCursor = waitForInitialization(this);
@@ -291,7 +304,10 @@ AggregationCursor.prototype._destroy = function _destroy(_err, callback) {
291
304
  .then(() => this.cursor?.close())
292
305
  .then(() => {
293
306
  this._closed = true;
294
- 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);
295
311
  })
296
312
  .catch(error => {
297
313
  callback(error);
@@ -69,7 +69,10 @@ function QueryCursor(query) {
69
69
  '".'
70
70
  );
71
71
  this._markError(err);
72
- 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
+ }
73
76
  return;
74
77
  }
75
78
  this.skipped = true;
@@ -77,7 +80,10 @@ function QueryCursor(query) {
77
80
  return;
78
81
  }
79
82
  this._markError(err);
80
- 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
+ }
81
87
  return;
82
88
  }
83
89
  const { middleware, ...options } = query._optionsForExec();
@@ -113,7 +119,8 @@ function QueryCursor(query) {
113
119
  };
114
120
 
115
121
  const preFilter = buildMiddlewareFilter(query.options, 'pre');
116
- 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));
117
124
  }
118
125
 
119
126
  util.inherits(QueryCursor, Readable);
@@ -131,7 +138,10 @@ function _getRawCursor(query, queryCursor) {
131
138
  } catch (err) {
132
139
  queryCursor._initializationComplete = true;
133
140
  queryCursor._markError(err);
134
- 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
+ }
135
145
  }
136
146
  }
137
147
 
@@ -146,6 +156,7 @@ function _getRawCursor(query, queryCursor) {
146
156
  QueryCursor.prototype._read = function() {
147
157
  _next(this, (error, doc) => {
148
158
  if (error) {
159
+ this._errorEmitted = true;
149
160
  return this.emit('error', error);
150
161
  }
151
162
  if (!doc) {
@@ -260,7 +271,10 @@ QueryCursor.prototype.close = async function close() {
260
271
  this._closed = true;
261
272
  this.emit('close');
262
273
  } catch (error) {
263
- 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
+ }
264
278
  throw error;
265
279
  }
266
280
  };
@@ -274,7 +288,7 @@ QueryCursor.prototype.close = async function close() {
274
288
  * @method _destroy
275
289
  */
276
290
 
277
- QueryCursor.prototype._destroy = function _destroy(_err, callback) {
291
+ QueryCursor.prototype._destroy = function _destroy(error, callback) {
278
292
  let waitForCursor = null;
279
293
  if (!this._initializationComplete) {
280
294
  waitForCursor = waitForInitialization(this);
@@ -288,7 +302,10 @@ QueryCursor.prototype._destroy = function _destroy(_err, callback) {
288
302
  })
289
303
  .then(() => {
290
304
  this._closed = true;
291
- 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);
292
309
  })
293
310
  .catch(error => {
294
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)) {
@@ -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
  }
@@ -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
  }
package/lib/model.js CHANGED
@@ -3059,7 +3059,7 @@ Model.startSession = function() {
3059
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()`.
3060
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`.
3061
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()).
3062
- * @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.
3063
3063
  * @param {string|object|Array} [options.populate=null] populates the result documents. This option is a no-op if `rawResult` is set.
3064
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.
3065
3065
  * @param {boolean|object} [options.middleware=true] set to `false` to skip all user-defined middleware
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
@@ -169,23 +169,31 @@ function Query(conditions, options, model, collection) {
169
169
  }
170
170
  }
171
171
 
172
- // 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.
173
174
  function isEmptyFilter(obj) {
174
175
  if (obj == null) return true;
175
176
  if (typeof obj !== 'object') return true;
176
- if (utils.hasOwnKeys(obj) === false) return true;
177
-
178
- // Check $and, $or, $nor arrays
179
- for (const key of ['$and', '$or', '$nor']) {
180
- if (Array.isArray(obj[key])) {
181
- // If array is empty or all elements are empty objects, consider it empty
182
- if (obj[key].length === 0 || obj[key].every(item => isEmptyFilter(item))) {
183
- return true;
184
- }
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;
185
189
  }
190
+ if (key === '$or' && (val.length === 0 || val.some(isEmptyFilter))) {
191
+ continue;
192
+ }
193
+ return false;
186
194
  }
187
195
 
188
- return false;
196
+ return true;
189
197
  }
190
198
 
191
199
  // Helper function to check for empty/invalid filter
@@ -1139,6 +1147,11 @@ Query.prototype.select = function select() {
1139
1147
  }
1140
1148
  arg = parseProjection(arg, true); // we want to keep the minus and pluses, so add boolean arg.
1141
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
+ }
1142
1155
  if (this.selectedInclusively()) {
1143
1156
  Object.entries(arg).forEach(([key, value]) => {
1144
1157
  if (value) {
@@ -4298,15 +4311,34 @@ Query.prototype._replaceOne = async function _replaceOne() {
4298
4311
  }
4299
4312
 
4300
4313
  const options = this._optionsForExec(this.model);
4301
- this[queryUpdateSymbol] = new this.model(this[queryUpdateSymbol], null, { skipId: true });
4302
- removeUnusedArrayFilters(this[queryUpdateSymbol], options);
4303
-
4304
- if (_getOption(this, 'runValidators', false)) {
4305
- await this.validate(this[queryUpdateSymbol], options, true);
4314
+ const modelOpts = { skipId: true };
4315
+ if ('strict' in this._mongooseOptions) {
4316
+ modelOpts.strict = this._mongooseOptions.strict;
4306
4317
  }
4307
4318
 
4308
- if (typeof this[queryUpdateSymbol].toBSON === 'function') {
4309
- 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;
4310
4342
  }
4311
4343
 
4312
4344
  return this.mongooseCollection.replaceOne(this._conditions, this[queryUpdateSymbol], options);
@@ -5257,11 +5289,7 @@ Query.prototype._castFields = function _castFields(fields) {
5257
5289
 
5258
5290
  if (selected) {
5259
5291
  // they passed $elemMatch, cast em
5260
- try {
5261
- out = this.cast(this.model, selected);
5262
- } catch (err) {
5263
- return err;
5264
- }
5292
+ out = this.cast(this.model, selected);
5265
5293
 
5266
5294
  // apply the casted field args
5267
5295
  for (let i = 0; i < elemMatchKeys.length; ++i) {
@@ -5284,19 +5312,30 @@ Query.prototype._applyPaths = function applyPaths() {
5284
5312
  }
5285
5313
  this._fields = this._fields || {};
5286
5314
 
5287
- let sanitizeProjection = undefined;
5315
+ let shouldSanitizeProjection = undefined;
5288
5316
  if (this.model != null && utils.hasUserDefinedProperty(this.model.db.options, 'sanitizeProjection')) {
5289
- sanitizeProjection = this.model.db.options.sanitizeProjection;
5317
+ shouldSanitizeProjection = this.model.db.options.sanitizeProjection;
5290
5318
  } else if (this.model != null && utils.hasUserDefinedProperty(this.model.base.options, 'sanitizeProjection')) {
5291
- sanitizeProjection = this.model.base.options.sanitizeProjection;
5319
+ shouldSanitizeProjection = this.model.base.options.sanitizeProjection;
5292
5320
  } else {
5293
- 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);
5294
5327
  }
5295
5328
 
5296
5329
  const schemaLevelProjections = this._mongooseOptions.schemaLevelProjections ?? true;
5297
5330
 
5298
5331
  if (schemaLevelProjections) {
5299
- 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);
5300
5339
  }
5301
5340
 
5302
5341
  let _selectPopulatedPaths = true;
@@ -12,6 +12,8 @@ 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');
17
19
  const setInheritedReadOptions = require('./helpers/populate/setInheritedReadOptions');
@@ -145,6 +147,16 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
145
147
  const minusPathsToSkip = new Set();
146
148
 
147
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
+
148
160
  keys = Object.keys(fields);
149
161
 
150
162
  // Collapse minus paths
@@ -164,6 +176,7 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
164
176
  }
165
177
 
166
178
  keys = Object.keys(fields);
179
+ let hasElemMatch = false;
167
180
  for (let keyIndex = 0; keyIndex < keys.length; ++keyIndex) {
168
181
  if (keys[keyIndex][0] === '+') {
169
182
  continue;
@@ -173,15 +186,32 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
173
186
  if (!isDefiningProjection(field)) {
174
187
  continue;
175
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
+ }
176
194
  if (keys[keyIndex] === '_id' && keys.length > 1) {
177
195
  continue;
178
196
  }
179
197
  if (keys[keyIndex] === schema.options.discriminatorKey && keys.length > 1 && field != null && !field) {
180
198
  continue;
181
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
+ }
182
209
  exclude = !field;
183
210
  break;
184
211
  }
212
+ if (exclude === undefined && hasElemMatch) {
213
+ exclude = false;
214
+ }
185
215
 
186
216
  // Potentially add back minus paths based on schema-level path config
187
217
  // and whether the projection is inclusive
@@ -214,6 +244,13 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
214
244
  if (schema._hasSelectedPaths !== false) {
215
245
  analyzeSchema(schema);
216
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
+ }
217
254
  switch (exclude) {
218
255
  case true:
219
256
  for (const fieldName of excluded) {
@@ -281,7 +318,10 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
281
318
  if (type.$isSchemaMap || path.endsWith('.$*')) {
282
319
  const plusPath = '+' + path;
283
320
  const hasPlusPath = fields && plusPath in fields;
284
- 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) {
285
325
  excluded.push(path);
286
326
  }
287
327
  return;
@@ -321,12 +361,11 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
321
361
  return;
322
362
  }
323
363
 
324
- // User overwriting default exclusion
325
- if (type.selected === false && fields[path]) {
326
- if (sanitizeProjection) {
327
- fields[path] = 0;
328
- }
329
-
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
330
369
  return;
331
370
  }
332
371
 
@@ -351,10 +390,8 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
351
390
 
352
391
  // if there are other fields being included, add this one
353
392
  // if no other included fields, leave this out (implied inclusion)
354
- if (exclude === false && keys.length > 1 && !~keys.indexOf(path) && !sanitizeProjection) {
393
+ if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) {
355
394
  fields[path] = 1;
356
- } else if (exclude == null && sanitizeProjection && type.selected === false) {
357
- fields[path] = 0;
358
395
  }
359
396
 
360
397
  return;
@@ -388,6 +425,21 @@ exports.applyPaths = function applyPaths(fields, schema, sanitizeProjection) {
388
425
  return path;
389
426
  }
390
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
+
391
443
  function hasExcludedAncestor(fields, path) {
392
444
  let i = -1;
393
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;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "9.12.1",
4
+ "version": "9.12.2",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -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