mongoose 8.13.3 → 8.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/document.js CHANGED
@@ -2620,7 +2620,6 @@ Document.prototype.validate = async function validate(pathsToValidate, options)
2620
2620
  if (typeof pathsToValidate === 'function' || typeof options === 'function' || typeof arguments[2] === 'function') {
2621
2621
  throw new MongooseError('Document.prototype.validate() no longer accepts a callback');
2622
2622
  }
2623
- let parallelValidate;
2624
2623
  this.$op = 'validate';
2625
2624
 
2626
2625
  if (arguments.length === 1) {
@@ -2638,16 +2637,9 @@ Document.prototype.validate = async function validate(pathsToValidate, options)
2638
2637
  if (this.$isSubdocument != null) {
2639
2638
  // Skip parallel validate check for subdocuments
2640
2639
  } else if (this.$__.validating && !_skipParallelValidateCheck) {
2641
- parallelValidate = new ParallelValidateError(this, {
2642
- parentStack: options && options.parentStack,
2643
- conflictStack: this.$__.validating.stack
2644
- });
2640
+ throw new ParallelValidateError(this);
2645
2641
  } else if (!_skipParallelValidateCheck) {
2646
- this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack });
2647
- }
2648
-
2649
- if (parallelValidate != null) {
2650
- throw parallelValidate;
2642
+ this.$__.validating = true;
2651
2643
  }
2652
2644
 
2653
2645
  return new Promise((resolve, reject) => {
@@ -3818,6 +3810,8 @@ Document.prototype.$toObject = function(options, json) {
3818
3810
  let _minimize;
3819
3811
  if (options._calledWithOptions.minimize != null) {
3820
3812
  _minimize = options.minimize;
3813
+ } else if (this.$__schemaTypeOptions?.minimize != null) {
3814
+ _minimize = this.$__schemaTypeOptions.minimize;
3821
3815
  } else if (defaultOptions != null && defaultOptions.minimize != null) {
3822
3816
  _minimize = defaultOptions.minimize;
3823
3817
  } else {
@@ -57,7 +57,6 @@ function clone(obj, options, isArrayChild) {
57
57
  return clonedDoc;
58
58
  }
59
59
  }
60
- const isSingleNested = obj.$isSingleNested;
61
60
 
62
61
  if (isPOJO(obj) && obj.$__ != null && obj._doc != null) {
63
62
  return obj._doc;
@@ -70,10 +69,6 @@ function clone(obj, options, isArrayChild) {
70
69
  ret = obj.toObject(options);
71
70
  }
72
71
 
73
- if (options && options.minimize && !obj.constructor.$__required && isSingleNested && Object.keys(ret).length === 0) {
74
- return undefined;
75
- }
76
-
77
72
  return ret;
78
73
  }
79
74
 
package/lib/model.js CHANGED
@@ -2307,9 +2307,14 @@ Model.$where = function $where() {
2307
2307
  *
2308
2308
  * #### Example:
2309
2309
  *
2310
- * A.findOneAndUpdate(conditions, update, options) // returns Query
2311
- * A.findOneAndUpdate(conditions, update) // returns Query
2312
- * A.findOneAndUpdate() // returns Query
2310
+ * A.findOneAndUpdate(filter, update, options); // returns Query
2311
+ * A.findOneAndUpdate(filter, update); // returns Query
2312
+ * A.findOneAndUpdate(filter); // returns Query
2313
+ * A.findOneAndUpdate(); // returns Query
2314
+ *
2315
+ * // Other supported syntaxes
2316
+ * // Note that calling `Query#findOneAndUpdate()` with 1 arg will treat the arg as `update`, NOT `filter`
2317
+ * A.find(filter).findOneAndUpdate(update);
2313
2318
  *
2314
2319
  * #### Note:
2315
2320
  *
@@ -2318,10 +2323,10 @@ Model.$where = function $where() {
2318
2323
  * #### Example:
2319
2324
  *
2320
2325
  * const query = { name: 'borne' };
2321
- * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options)
2326
+ * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options);
2322
2327
  *
2323
2328
  * // is sent as
2324
- * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options)
2329
+ * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options);
2325
2330
  *
2326
2331
  * #### Note:
2327
2332
  *
@@ -2366,12 +2371,6 @@ Model.findOneAndUpdate = function(conditions, update, options) {
2366
2371
  throw new MongooseError('Model.findOneAndUpdate() no longer accepts a callback');
2367
2372
  }
2368
2373
 
2369
- if (arguments.length === 1) {
2370
- update = conditions;
2371
- conditions = null;
2372
- options = null;
2373
- }
2374
-
2375
2374
  let fields;
2376
2375
  if (options) {
2377
2376
  fields = options.fields || options.projection;
@@ -31,7 +31,7 @@ const opts = require('./propertyOptions');
31
31
  * parentSchema.path('child').schema.options._id; // false
32
32
  *
33
33
  * @api public
34
- * @property of
34
+ * @property _id
35
35
  * @memberOf SchemaSubdocumentOptions
36
36
  * @type {Function|string}
37
37
  * @instance
@@ -39,4 +39,28 @@ const opts = require('./propertyOptions');
39
39
 
40
40
  Object.defineProperty(SchemaSubdocumentOptions.prototype, '_id', opts);
41
41
 
42
+ /**
43
+ * If set, overwrites the child schema's `minimize` option. In addition, configures whether the entire
44
+ * subdocument can be minimized out.
45
+ *
46
+ * #### Example:
47
+ *
48
+ * const childSchema = Schema({ name: String });
49
+ * const parentSchema = Schema({
50
+ * child: { type: childSchema, minimize: false }
51
+ * });
52
+ * const ParentModel = mongoose.model('Parent', parentSchema);
53
+ * // Saves `{ child: {} }` to the db. Without `minimize: false`, Mongoose would remove the empty
54
+ * // object and save `{}` to the db.
55
+ * await ParentModel.create({ child: {} });
56
+ *
57
+ * @api public
58
+ * @property minimize
59
+ * @memberOf SchemaSubdocumentOptions
60
+ * @type {Function|string}
61
+ * @instance
62
+ */
63
+
64
+ Object.defineProperty(SchemaSubdocumentOptions.prototype, 'minimize', opts);
65
+
42
66
  module.exports = SchemaSubdocumentOptions;
package/lib/query.js CHANGED
@@ -3307,17 +3307,18 @@ function prepareDiscriminatorCriteria(query) {
3307
3307
  * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
3308
3308
  * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.
3309
3309
  * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()`
3310
- * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
3310
+ * - `sort`: if multiple docs are found by the filter, sets the sort order to choose which doc to update
3311
3311
  * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0
3312
3312
  * - `runValidators`: if true, runs [update validators](https://mongoosejs.com/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema.
3313
3313
  * - `setDefaultsOnInsert`: `true` by default. If `setDefaultsOnInsert` and `upsert` are true, mongoose will apply the [defaults](https://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created.
3314
3314
  *
3315
3315
  * #### Example:
3316
3316
  *
3317
- * query.findOneAndUpdate(conditions, update, options) // returns Query
3318
- * query.findOneAndUpdate(conditions, update) // returns Query
3319
- * query.findOneAndUpdate(update) // returns Query
3320
- * query.findOneAndUpdate() // returns Query
3317
+ * query.findOneAndUpdate(filter, update, options); // returns Query
3318
+ * query.findOneAndUpdate(filter, update); // returns Query
3319
+ * // Note that `Query#findOneAndUpdate()` with 1 arg treats the first arg as the `update`, NOT the `filter`.
3320
+ * query.findOneAndUpdate(update); // returns Query
3321
+ * query.findOneAndUpdate(); // returns Query
3321
3322
  *
3322
3323
  * @method findOneAndUpdate
3323
3324
  * @memberOf Query
@@ -3331,8 +3332,6 @@ function prepareDiscriminatorCriteria(query) {
3331
3332
  * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
3332
3333
  * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied.
3333
3334
  * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.lean()) and [the Mongoose lean tutorial](https://mongoosejs.com/docs/tutorials/lean.html).
3334
- * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](https://mongoosejs.com/docs/transactions.html).
3335
- * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict)
3336
3335
  * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
3337
3336
  * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
3338
3337
  * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `filter`, `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.
@@ -3724,6 +3723,99 @@ Query.prototype._findOneAndReplace = async function _findOneAndReplace() {
3724
3723
  });
3725
3724
  };
3726
3725
 
3726
+ /**
3727
+ * Finds a single document by its _id field. `findById(id)` is equivalent to
3728
+ * `findOne({ _id: id })`.
3729
+ *
3730
+ * The `id` is cast based on the Schema before sending the command.
3731
+ *
3732
+ * This function triggers the following middleware.
3733
+ *
3734
+ * - `findOne()`
3735
+ *
3736
+ * @method findById
3737
+ * @memberOf Query
3738
+ * @instance
3739
+ * @param {Any} id value of `_id` to query by
3740
+ * @param {Object} [projection] optional fields to return
3741
+ * @param {Object} [options] see [`setOptions()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.setOptions())
3742
+ * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.
3743
+ * @return {Query} this
3744
+ * @see findOne https://www.mongodb.com/docs/manual/reference/method/db.collection.findOne/
3745
+ * @see Query.select https://mongoosejs.com/docs/api/query.html#Query.prototype.select()
3746
+ * @api public
3747
+ */
3748
+
3749
+ Query.prototype.findById = function(id, projection, options) {
3750
+ return this.findOne({ _id: id }, projection, options);
3751
+ };
3752
+
3753
+
3754
+ /**
3755
+ * Issues a mongodb findOneAndUpdate command by a document's _id field.
3756
+ * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`.
3757
+ *
3758
+ * Finds a matching document, updates it according to the `update` arg,
3759
+ * passing any `options`, and returns the found document (if any).
3760
+ *
3761
+ * This function triggers the following middleware.
3762
+ *
3763
+ * - `findOneAndUpdate()`
3764
+ *
3765
+ * @method findByIdAndUpdate
3766
+ * @memberOf Query
3767
+ * @instance
3768
+ * @param {Any} id value of `_id` to query by
3769
+ * @param {Object} [doc]
3770
+ * @param {Object} [options]
3771
+ * @param {Boolean} [options.includeResultMetadata] if true, returns the full [ModifyResult from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/ModifyResult.html) rather than just the document
3772
+ * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict)
3773
+ * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](https://mongoosejs.com/docs/transactions.html).
3774
+ * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
3775
+ * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied.
3776
+ * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.lean()) and [the Mongoose lean tutorial](https://mongoosejs.com/docs/tutorials/lean.html).
3777
+ * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](https://mongoosejs.com/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.
3778
+ * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
3779
+ * @param {Boolean} [options.translateAliases=null] If set to `true`, translates any schema-defined aliases in `projection`, `update`, and `distinct`. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.
3780
+ * @param {Boolean} [options.overwriteDiscriminatorKey=false] Mongoose removes discriminator key updates from `update` by default, set `overwriteDiscriminatorKey` to `true` to allow updating the discriminator key
3781
+ * @param {Boolean} [options.overwriteImmutable=false] Mongoose removes updated immutable properties from `update` by default (excluding $setOnInsert). Set `overwriteImmutable` to `true` to allow updating immutable properties using other update operators.
3782
+ * @see Tutorial https://mongoosejs.com/docs/tutorials/findoneandupdate.html
3783
+ * @see findAndModify command https://www.mongodb.com/docs/manual/reference/command/findAndModify/
3784
+ * @see ModifyResult https://mongodb.github.io/node-mongodb-native/4.9/interfaces/ModifyResult.html
3785
+ * @see findOneAndUpdate https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#findOneAndUpdate
3786
+ * @return {Query} this
3787
+ * @api public
3788
+ */
3789
+
3790
+ Query.prototype.findByIdAndUpdate = function(id, update, options) {
3791
+ return this.findOneAndUpdate({ _id: id }, update, options);
3792
+ };
3793
+
3794
+ /**
3795
+ * Issue a MongoDB `findOneAndDelete()` command by a document's _id field.
3796
+ * In other words, `findByIdAndDelete(id)` is a shorthand for
3797
+ * `findOneAndDelete({ _id: id })`.
3798
+ *
3799
+ * This function triggers the following middleware.
3800
+ *
3801
+ * - `findOneAndDelete()`
3802
+ *
3803
+ * @method findByIdAndDelete
3804
+ * @memberOf Query
3805
+ * @param {any} id value of `_id` to query by
3806
+ * @param {Object} [options]
3807
+ * @param {Boolean} [options.includeResultMetadata] if true, returns the full [ModifyResult from the MongoDB driver](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/ModifyResult.html) rather than just the document
3808
+ * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](https://mongoosejs.com/docs/transactions.html).
3809
+ * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](https://mongoosejs.com/docs/guide.html#strict)
3810
+ * @return {Query} this
3811
+ * @see findAndModify command https://www.mongodb.com/docs/manual/reference/command/findAndModify/
3812
+ * @api public
3813
+ */
3814
+
3815
+ Query.prototype.findByIdAndDelete = function(id, options) {
3816
+ return this.findOneAndDelete({ _id: id }, options);
3817
+ };
3818
+
3727
3819
  /**
3728
3820
  * Support the `new` option as an alternative to `returnOriginal` for backwards
3729
3821
  * compat.
@@ -4429,10 +4521,12 @@ Query.prototype.exec = async function exec(op) {
4429
4521
  str = str.slice(0, 60) + '...';
4430
4522
  }
4431
4523
  const err = new MongooseError('Query was already executed: ' + str);
4432
- err.originalStack = this._executionStack;
4524
+ if (!this.model.base.options.skipOriginalStackTraces) {
4525
+ err.originalStack = this._executionStack;
4526
+ }
4433
4527
  throw err;
4434
4528
  } else {
4435
- this._executionStack = new Error().stack;
4529
+ this._executionStack = this.model.base.options.skipOriginalStackTraces ? true : new Error().stack;
4436
4530
  }
4437
4531
 
4438
4532
  let skipWrappedFunction = null;
@@ -90,6 +90,7 @@ function _createConstructor(schema, baseClass, options) {
90
90
  _embedded.prototype = Object.create(proto);
91
91
  _embedded.prototype.$__setSchema(schema);
92
92
  _embedded.prototype.constructor = _embedded;
93
+ _embedded.prototype.$__schemaTypeOptions = options;
93
94
  _embedded.$__required = options?.required;
94
95
  _embedded.base = schema.base;
95
96
  _embedded.schema = schema;
@@ -412,6 +412,25 @@ if (util.inspect.custom) {
412
412
  Subdocument.prototype[util.inspect.custom] = Subdocument.prototype.inspect;
413
413
  }
414
414
 
415
+ /**
416
+ * Override `$toObject()` to handle minimizing the whole path. Should not minimize if schematype-level minimize
417
+ * is set to false re: gh-11247, gh-14058, gh-14151
418
+ */
419
+
420
+ Subdocument.prototype.$toObject = function $toObject(options, json) {
421
+ const ret = Document.prototype.$toObject.call(this, options, json);
422
+
423
+ // If `$toObject()` was called recursively, respect the minimize option, including schematype level minimize.
424
+ // If minimize is set, then we can minimize out the whole object.
425
+ if (Object.keys(ret).length === 0 && options?._calledWithOptions != null) {
426
+ const minimize = options._calledWithOptions?.minimize ?? this?.$__schemaTypeOptions?.minimize ?? options.minimize;
427
+ if (minimize && !this.constructor.$__required) {
428
+ return undefined;
429
+ }
430
+ }
431
+ return ret;
432
+ };
433
+
415
434
  /**
416
435
  * Registers remove event listeners for triggering
417
436
  * on subdocuments.
@@ -29,6 +29,7 @@ const VALID_OPTIONS = Object.freeze([
29
29
  'sanitizeProjection',
30
30
  'selectPopulatedPaths',
31
31
  'setDefaultsOnInsert',
32
+ 'skipOriginalStackTraces',
32
33
  'strict',
33
34
  'strictPopulate',
34
35
  'strictQuery',
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "8.13.3",
4
+ "version": "8.14.0",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -22,7 +22,7 @@
22
22
  "dependencies": {
23
23
  "bson": "^6.10.3",
24
24
  "kareem": "2.6.3",
25
- "mongodb": "~6.15.0",
25
+ "mongodb": "~6.16.0",
26
26
  "mpath": "0.9.0",
27
27
  "mquery": "5.0.0",
28
28
  "ms": "2.1.3",
@@ -18,7 +18,7 @@ declare module 'mongoose' {
18
18
  * * TQueryHelpers - Object with any helpers that should be mixed into the Query type
19
19
  * * DocType - the type of the actual Document created
20
20
  */
21
- class Document<T = unknown, TQueryHelpers = any, DocType = any> {
21
+ class Document<T = unknown, TQueryHelpers = any, DocType = any, TVirtuals = Record<string, any>> {
22
22
  constructor(doc?: any);
23
23
 
24
24
  /** This documents _id. */
@@ -256,6 +256,7 @@ declare module 'mongoose' {
256
256
  set(value: string | Record<string, any>): this;
257
257
 
258
258
  /** The return value of this method is used in calls to JSON.stringify(doc). */
259
+ toJSON(options: ToObjectOptions & { virtuals: true }): Default__v<Require_id<DocType & TVirtuals>>;
259
260
  toJSON(options?: ToObjectOptions & { flattenMaps?: true, flattenObjectIds?: false }): FlattenMaps<Default__v<Require_id<DocType>>>;
260
261
  toJSON(options: ToObjectOptions & { flattenObjectIds: false }): FlattenMaps<Default__v<Require_id<DocType>>>;
261
262
  toJSON(options: ToObjectOptions & { flattenObjectIds: true }): ObjectIdToString<FlattenMaps<Default__v<Require_id<DocType>>>>;
@@ -269,6 +270,7 @@ declare module 'mongoose' {
269
270
  toJSON<T = Default__v<Require_id<DocType>>>(options: ToObjectOptions & { flattenMaps: false; flattenObjectIds: true }): ObjectIdToString<T>;
270
271
 
271
272
  /** Converts this document into a plain-old JavaScript object ([POJO](https://masteringjs.io/tutorials/fundamentals/pojo)). */
273
+ toObject(options: ToObjectOptions & { virtuals: true }): Default__v<Require_id<DocType & TVirtuals>>;
272
274
  toObject(options?: ToObjectOptions): Default__v<Require_id<DocType>>;
273
275
  toObject<T>(options?: ToObjectOptions): Default__v<Require_id<T>>;
274
276
 
package/types/index.d.ts CHANGED
@@ -90,7 +90,8 @@ declare module 'mongoose' {
90
90
  HydratedDocument<
91
91
  InferSchemaType<TSchema>,
92
92
  ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
93
- ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>
93
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
94
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>
94
95
  >,
95
96
  TSchema
96
97
  > & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
@@ -146,16 +147,17 @@ declare module 'mongoose' {
146
147
  export type HydratedDocument<
147
148
  DocType,
148
149
  TOverrides = {},
149
- TQueryHelpers = {}
150
+ TQueryHelpers = {},
151
+ TVirtuals = {}
150
152
  > = IfAny<
151
153
  DocType,
152
154
  any,
153
155
  TOverrides extends Record<string, never> ?
154
- Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>> :
156
+ Document<unknown, TQueryHelpers, DocType, TVirtuals> & Default__v<Require_id<DocType>> :
155
157
  IfAny<
156
158
  TOverrides,
157
- Document<unknown, TQueryHelpers, DocType> & Default__v<Require_id<DocType>>,
158
- Document<unknown, TQueryHelpers, DocType> & MergeType<
159
+ Document<unknown, TQueryHelpers, DocType, TVirtuals> & Default__v<Require_id<DocType>>,
160
+ Document<unknown, TQueryHelpers, DocType, TVirtuals> & MergeType<
159
161
  Default__v<Require_id<DocType>>,
160
162
  TOverrides
161
163
  >
@@ -195,8 +197,9 @@ declare module 'mongoose' {
195
197
 
196
198
  export type HydratedDocumentFromSchema<TSchema extends Schema> = HydratedDocument<
197
199
  InferSchemaType<TSchema>,
198
- ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
199
- ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>
200
+ ObtainSchemaGeneric<TSchema, 'TInstanceMethods'> & ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
201
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
202
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>
200
203
  >;
201
204
 
202
205
  export interface TagSet {
@@ -269,7 +272,7 @@ declare module 'mongoose' {
269
272
  ObtainDocumentType<any, RawDocType, ResolveSchemaOptions<TSchemaOptions>>,
270
273
  ResolveSchemaOptions<TSchemaOptions>
271
274
  >,
272
- THydratedDocumentType = HydratedDocument<FlatRecord<DocType>, TVirtuals & TInstanceMethods>
275
+ THydratedDocumentType = HydratedDocument<FlatRecord<DocType>, TVirtuals & TInstanceMethods, {}, TVirtuals>
273
276
  >
274
277
  extends events.EventEmitter {
275
278
  /**
@@ -436,6 +439,7 @@ declare module 'mongoose' {
436
439
  ): this;
437
440
  // this = Document
438
441
  pre<T = THydratedDocumentType>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
442
+ pre<T = THydratedDocumentType, U = RawDocType>(method: 'init', fn: (this: T, doc: U) => void): this;
439
443
  pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PreMiddlewareFunction<T>): this;
440
444
  pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
441
445
  pre<T = THydratedDocumentType>(
@@ -22,7 +22,7 @@ declare module 'mongoose' {
22
22
 
23
23
  /**
24
24
  * @summary Obtains schema Path type.
25
- * @description Obtains Path type by separating path type from other options and calling {@link ResolvePathType}
25
+ * @description Obtains Path type by separating path type from other options and calling {@link ResolveRawPathType}
26
26
  * @param {PathValueType} PathValueType Document definition path type.
27
27
  * @param {TypeKey} TypeKey A generic refers to document definition.
28
28
  */
@@ -61,14 +61,14 @@ declare module 'mongoose' {
61
61
  // so we can directly obtain its path type.
62
62
  ObtainRawDocumentPathType<Item, TypeKey>[] :
63
63
  // If the type key isn't callable, then this is an array of objects, in which case
64
- // we need to call ObtainDocumentType to correctly infer its type.
65
- Array<ObtainDocumentType<Item, any, { typeKey: TypeKey }>> :
64
+ // we need to call InferRawDocType to correctly infer its type.
65
+ Array<InferRawDocType<Item>> :
66
66
  IsSchemaTypeFromBuiltinClass<Item> extends true ?
67
67
  ObtainRawDocumentPathType<Item, TypeKey>[] :
68
68
  IsItRecordAndNotAny<Item> extends true ?
69
69
  Item extends Record<string, never> ?
70
70
  ObtainRawDocumentPathType<Item, TypeKey>[] :
71
- Array<ObtainDocumentType<Item, any, { typeKey: TypeKey }>> :
71
+ Array<InferRawDocType<Item>> :
72
72
  ObtainRawDocumentPathType<Item, TypeKey>[]
73
73
  >:
74
74
  PathValueType extends ReadonlyArray<infer Item> ?
@@ -77,13 +77,13 @@ declare module 'mongoose' {
77
77
  Item extends Record<TypeKey, any> ?
78
78
  Item[TypeKey] extends Function | String ?
79
79
  ObtainRawDocumentPathType<Item, TypeKey>[] :
80
- ObtainDocumentType<Item, any, { typeKey: TypeKey }>[]:
80
+ InferRawDocType<Item>[]:
81
81
  IsSchemaTypeFromBuiltinClass<Item> extends true ?
82
82
  ObtainRawDocumentPathType<Item, TypeKey>[] :
83
83
  IsItRecordAndNotAny<Item> extends true ?
84
84
  Item extends Record<string, never> ?
85
85
  ObtainRawDocumentPathType<Item, TypeKey>[] :
86
- Array<ObtainDocumentType<Item, any, { typeKey: TypeKey }>> :
86
+ Array<InferRawDocType<Item>> :
87
87
  ObtainRawDocumentPathType<Item, TypeKey>[]
88
88
  >:
89
89
  PathValueType extends StringSchemaDefinition ? PathEnumOrString<Options['enum']> :
@@ -114,6 +114,6 @@ declare module 'mongoose' {
114
114
  IfEquals<PathValueType, ObjectConstructor> extends true ? any:
115
115
  IfEquals<PathValueType, {}> extends true ? any:
116
116
  PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
117
- PathValueType extends Record<string, any> ? ObtainDocumentType<PathValueType, any, { typeKey: TypeKey }> :
117
+ PathValueType extends Record<string, any> ? InferRawDocType<PathValueType> :
118
118
  unknown;
119
119
  }
@@ -3,7 +3,7 @@ declare module 'mongoose' {
3
3
 
4
4
  type MongooseQueryAndDocumentMiddleware = 'updateOne' | 'deleteOne';
5
5
 
6
- type MongooseDistinctDocumentMiddleware = 'save' | 'init' | 'validate';
6
+ type MongooseDistinctDocumentMiddleware = 'save' | 'validate';
7
7
  type MongooseDocumentMiddleware = MongooseDistinctDocumentMiddleware | MongooseQueryAndDocumentMiddleware;
8
8
 
9
9
  type MongooseRawResultQueryMiddleware = 'findOneAndUpdate' | 'findOneAndReplace' | 'findOneAndDelete';
package/types/models.d.ts CHANGED
@@ -263,7 +263,7 @@ declare module 'mongoose' {
263
263
  TQueryHelpers = {},
264
264
  TInstanceMethods = {},
265
265
  TVirtuals = {},
266
- THydratedDocumentType = HydratedDocument<TRawDocType, TVirtuals & TInstanceMethods, TQueryHelpers>,
266
+ THydratedDocumentType = HydratedDocument<TRawDocType, TVirtuals & TInstanceMethods, TQueryHelpers, TVirtuals>,
267
267
  TSchema = any> extends
268
268
  NodeJS.EventEmitter,
269
269
  AcceptsDiscriminator,
@@ -215,5 +215,13 @@ declare module 'mongoose' {
215
215
  * to their database property names. Defaults to false.
216
216
  */
217
217
  translateAliases?: boolean;
218
+
219
+ /**
220
+ * Mongoose queries currently store an `_executionStack` property that stores the stack trace
221
+ * of where the query was originally executed for debugging `Query was already executed` errors.
222
+ * This behavior can cause performance issues with bundlers and source maps. Set this option to
223
+ * `true` to disable Mongoose query stack trace collection.
224
+ */
225
+ skipOriginalStackTraces?: boolean;
218
226
  }
219
227
  }
package/types/query.d.ts CHANGED
@@ -466,10 +466,14 @@ declare module 'mongoose' {
466
466
  options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc
467
467
  ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>;
468
468
  findOneAndUpdate(
469
- filter?: RootFilterQuery<RawDocType>,
470
- update?: UpdateQuery<RawDocType>,
469
+ filter: RootFilterQuery<RawDocType>,
470
+ update: UpdateQuery<RawDocType>,
471
471
  options?: QueryOptions<DocType> | null
472
472
  ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>;
473
+ findOneAndUpdate(
474
+ update: UpdateQuery<RawDocType>
475
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>;
476
+ findOneAndUpdate(): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides>;
473
477
 
474
478
  /** Declares the query a findById operation. When executed, returns the document with the given `_id`. */
475
479
  findById(
@@ -173,6 +173,9 @@ declare module 'mongoose' {
173
173
  /** The maximum value allowed for this path. Only allowed for numbers and dates. */
174
174
  max?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string];
175
175
 
176
+ /** Set to false to disable minimizing empty single nested subdocuments by default */
177
+ minimize?: boolean;
178
+
176
179
  /** Defines a TTL index on this path. Only allowed for dates. */
177
180
  expires?: string | number;
178
181