mongoose 6.5.2 → 6.5.3

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.
@@ -20,7 +20,7 @@ const isObject = require('./helpers/isObject');
20
20
  * @param {Object} schema
21
21
  * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
22
22
  * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
23
- * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#events_class_events_eventemitter
23
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
24
24
  * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose.
25
25
  * @event `save`: Emitted when the document is successfully saved
26
26
  * @api private
package/lib/connection.js CHANGED
@@ -42,7 +42,7 @@ const noPasswordAuthMechanisms = [
42
42
  * For practical reasons, a Connection equals a Db.
43
43
  *
44
44
  * @param {Mongoose} base a mongoose instance
45
- * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#events_class_events_eventemitter
45
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
46
46
  * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
47
47
  * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
48
48
  * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connection's models.
package/lib/document.js CHANGED
@@ -70,7 +70,7 @@ const specialProperties = utils.specialProperties;
70
70
  * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data
71
71
  * @param {Object} [options] various configuration options for the document
72
72
  * @param {Boolean} [options.defaults=true] if `false`, skip applying default values to this document.
73
- * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#events_class_events_eventemitter
73
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
74
74
  * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose.
75
75
  * @event `save`: Emitted when the document is successfully saved
76
76
  * @api private
@@ -4452,7 +4452,7 @@ Document.prototype.$assertPopulated = function $assertPopulated(paths) {
4452
4452
  *
4453
4453
  * If the path was not provided, then all populated fields are returned to their unpopulated state.
4454
4454
  *
4455
- * @param {String} [path] Specific Path to depopulate. If unset, will depopulate all paths on the Document.
4455
+ * @param {String|String[]} [path] Specific Path to depopulate. If unset, will depopulate all paths on the Document. Or multiple space-delimited paths.
4456
4456
  * @return {Document} this
4457
4457
  * @see Document.populate #document_Document-populate
4458
4458
  * @api public
@@ -0,0 +1,29 @@
1
+ /*!
2
+ * Module dependencies.
3
+ */
4
+
5
+ 'use strict';
6
+
7
+ const MongooseError = require('./');
8
+
9
+ class StrictPopulateError extends MongooseError {
10
+ /**
11
+ * Strict mode error constructor
12
+ *
13
+ * @param {String} path
14
+ * @param {String} [msg]
15
+ * @inherits MongooseError
16
+ * @api private
17
+ */
18
+ constructor(path, msg) {
19
+ msg = msg || 'Cannot populate path `' + path + '` because it is not in your schema. ' + 'Set the `strictPopulate` option to false to override.';
20
+ super(msg);
21
+ this.path = path;
22
+ }
23
+ }
24
+
25
+ Object.defineProperty(StrictPopulateError.prototype, 'name', {
26
+ value: 'StrictPopulateError'
27
+ });
28
+
29
+ module.exports = StrictPopulateError;
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const MongooseError = require('../../error/mongooseError');
4
+ const isMongooseObject = require('../isMongooseObject');
4
5
  const setDottedPath = require('../path/setDottedPath');
5
6
  const util = require('util');
6
7
 
@@ -13,8 +14,8 @@ module.exports = function flattenObjectWithDottedPaths(obj) {
13
14
  if (obj == null || typeof obj !== 'object' || Array.isArray(obj)) {
14
15
  return;
15
16
  }
16
- // Avoid Mongoose docs
17
- if (obj.$__) {
17
+ // Avoid Mongoose docs, like docs and maps, because these may cause infinite recursion
18
+ if (isMongooseObject(obj)) {
18
19
  return;
19
20
  }
20
21
  const keys = Object.keys(obj);
@@ -15,6 +15,7 @@ const utils = require('../../utils');
15
15
  const modelSymbol = require('../symbols').modelSymbol;
16
16
  const populateModelSymbol = require('../symbols').populateModelSymbol;
17
17
  const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
18
+ const StrictPopulate = require('../../error/strictPopulate');
18
19
 
19
20
  module.exports = function getModelsMapForPopulate(model, docs, options) {
20
21
  let doc;
@@ -44,9 +45,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
44
45
  allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null);
45
46
 
46
47
  if (allSchemaTypes.length === 0 && options.strictPopulate !== false && options._localModel != null) {
47
- return new MongooseError('Cannot populate path `' + (options._fullPath || options.path) +
48
- '` because it is not in your schema. Set the `strictPopulate` option ' +
49
- 'to false to override.');
48
+ return new StrictPopulate(options._fullPath || options.path);
50
49
  }
51
50
 
52
51
  for (let i = 0; i < len; i++) {
package/lib/index.js CHANGED
@@ -367,7 +367,7 @@ Mongoose.prototype.createConnection = function(uri, options, callback) {
367
367
  * @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.
368
368
  * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
369
369
  * @param {Function} [callback]
370
- * @see Mongoose#createConnection #index_Mongoose-createConnection
370
+ * @see Mongoose#createConnection /docs/api.html#mongoose_Mongoose-createConnection
371
371
  * @api public
372
372
  * @return {Promise} resolves to `this` if connection succeeded
373
373
  */
@@ -862,7 +862,7 @@ Mongoose.prototype.SchemaType = SchemaType;
862
862
  * _Alias of mongoose.Schema.Types for backwards compatibility._
863
863
  *
864
864
  * @property SchemaTypes
865
- * @see Schema.SchemaTypes #schema_Schema-Types
865
+ * @see Schema.SchemaTypes /docs/schematypes
866
866
  * @api public
867
867
  */
868
868
 
package/lib/model.js CHANGED
@@ -3520,23 +3520,23 @@ function _setIsNew(doc, val) {
3520
3520
  *
3521
3521
  * @param {Array} ops
3522
3522
  * @param {Object} [ops.insertOne.document] The document to insert
3523
- * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter
3524
- * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
3525
- * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match
3526
- * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
3527
- * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
3528
- * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
3529
- * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter
3530
- * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
3531
- * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter`
3532
- * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
3533
- * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
3534
- * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
3535
- * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter
3536
- * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter
3537
- * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter
3538
- * @param {Object} [opts.replaceOne.replacement] The replacement document
3539
- * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter`
3523
+ * @param {Object} [ops.updateOne.filter] Update the first document that matches this filter
3524
+ * @param {Object} [ops.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
3525
+ * @param {Boolean} [ops.updateOne.upsert=false] If true, insert a doc if none match
3526
+ * @param {Boolean} [ops.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
3527
+ * @param {Object} [ops.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
3528
+ * @param {Array} [ops.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
3529
+ * @param {Object} [ops.updateMany.filter] Update all the documents that match this filter
3530
+ * @param {Object} [ops.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/)
3531
+ * @param {Boolean} [ops.updateMany.upsert=false] If true, insert a doc if no documents match `filter`
3532
+ * @param {Boolean} [ops.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation
3533
+ * @param {Object} [ops.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use
3534
+ * @param {Array} [ops.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update`
3535
+ * @param {Object} [ops.deleteOne.filter] Delete the first document that matches this filter
3536
+ * @param {Object} [ops.deleteMany.filter] Delete all documents that match this filter
3537
+ * @param {Object} [ops.replaceOne.filter] Replace the first document that matches this filter
3538
+ * @param {Object} [ops.replaceOne.replacement] The replacement document
3539
+ * @param {Boolean} [ops.replaceOne.upsert=false] If true, insert a doc if no documents match `filter`
3540
3540
  * @param {Object} [options]
3541
3541
  * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
3542
3542
  * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html).
@@ -4704,7 +4704,7 @@ function populate(model, docs, options, callback) {
4704
4704
  */
4705
4705
 
4706
4706
  function _execPopulateQuery(mod, match, select, assignmentOpts, callback) {
4707
- const subPopulate = utils.clone(mod.options.populate);
4707
+ let subPopulate = utils.clone(mod.options.populate);
4708
4708
  const queryOptions = Object.assign({
4709
4709
  skip: mod.options.skip,
4710
4710
  limit: mod.options.limit,
@@ -4749,6 +4749,8 @@ function _execPopulateQuery(mod, match, select, assignmentOpts, callback) {
4749
4749
  if (mod.model.baseModelName != null) {
4750
4750
  if (Array.isArray(subPopulate)) {
4751
4751
  subPopulate.forEach(pop => { pop.strictPopulate = false; });
4752
+ } else if (typeof subPopulate === 'string') {
4753
+ subPopulate = { path: subPopulate, strictPopulate: false };
4752
4754
  } else {
4753
4755
  subPopulate.strictPopulate = false;
4754
4756
  }
@@ -392,7 +392,7 @@ DocumentArrayPath.prototype.getDefault = function(scope, init, options) {
392
392
  };
393
393
 
394
394
  const _toObjectOptions = Object.freeze({ transform: false, virtuals: false });
395
- const initDocumentOptions = Object.freeze({ skipId: true, willInit: true });
395
+ const initDocumentOptions = Object.freeze({ skipId: false, willInit: true });
396
396
 
397
397
  /**
398
398
  * Casts contents
package/lib/schema.js CHANGED
@@ -88,7 +88,7 @@ let id = 0;
88
88
  *
89
89
  * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
90
90
  * @param {Object} [options]
91
- * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#events_class_events_eventemitter
91
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
92
92
  * @event `init`: Emitted after the schema is compiled into a `Model`.
93
93
  * @api public
94
94
  */
@@ -1842,6 +1842,7 @@ Schema.prototype.static = function(name, fn) {
1842
1842
  * @param {Object} fields The Fields to index, with the order, available values: `1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'`
1843
1843
  * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex)
1844
1844
  * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
1845
+ * @param {String} [options.language_override=null] Tells mongodb to use the specified field instead of `language` for parsing text indexes.
1845
1846
  * @api public
1846
1847
  */
1847
1848
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mongoose",
3
3
  "description": "Mongoose MongoDB ODM",
4
- "version": "6.5.2",
4
+ "version": "6.5.3",
5
5
  "author": "Guillermo Rauch <guillermo@learnboost.com>",
6
6
  "keywords": [
7
7
  "mongodb",
@@ -45,6 +45,7 @@
45
45
  "dox": "0.9.1",
46
46
  "eslint": "8.21.0",
47
47
  "eslint-plugin-mocha-no-only": "1.1.1",
48
+ "express": "^4.18.1",
48
49
  "highlight.js": "11.6.0",
49
50
  "lodash.isequal": "4.5.0",
50
51
  "lodash.isequalwith": "4.4.0",
@@ -57,7 +58,6 @@
57
58
  "nyc": "15.1.0",
58
59
  "pug": "3.0.2",
59
60
  "q": "1.5.1",
60
- "serve-handler": "6.1.3",
61
61
  "sinon": "14.0.0",
62
62
  "stream-browserify": "3.0.0",
63
63
  "ts-benchmark": "^1.1.10",
@@ -150,11 +150,11 @@ declare module 'mongoose' {
150
150
  ): Model<InferSchemaType<TSchema>, ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>, ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>, {}, TSchema> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
151
151
  model<T, U, TQueryHelpers = {}>(
152
152
  name: string,
153
- schema?: Schema<T, U, any, TQueryHelpers, any, any>,
153
+ schema?: Schema<T, any, any, TQueryHelpers, any, any>,
154
154
  collection?: string,
155
155
  options?: CompileModelOptions
156
156
  ): U;
157
- model<T>(name: string, schema?: Schema<T>, collection?: string, options?: CompileModelOptions): Model<T>;
157
+ model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
158
158
 
159
159
  /** Returns an array of model names created on this connection. */
160
160
  modelNames(): Array<string>;
@@ -164,7 +164,7 @@ declare module 'mongoose' {
164
164
  invalidate(path: string, errorMsg: string | NativeError, value?: any, kind?: string): NativeError | null;
165
165
 
166
166
  /** Returns true if `path` was directly set and modified, else false. */
167
- isDirectModified(path: string): boolean;
167
+ isDirectModified(path: string | Array<string>): boolean;
168
168
 
169
169
  /** Checks if `path` was explicitly selected. If no projection, always returns true. */
170
170
  isDirectSelected(path: string): boolean;
package/types/index.d.ts CHANGED
@@ -62,7 +62,10 @@ declare module 'mongoose' {
62
62
  export function get<K extends keyof MongooseOptions>(key: K): MongooseOptions[K];
63
63
 
64
64
  /* ! ignore */
65
- export type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection };
65
+ export type CompileModelOptions = {
66
+ overwriteModels?: boolean,
67
+ connection?: Connection
68
+ };
66
69
 
67
70
  export function model<TSchema extends Schema = any>(
68
71
  name: string,
@@ -113,10 +116,6 @@ declare module 'mongoose' {
113
116
  ? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
114
117
  : T & { _id: Types.ObjectId };
115
118
 
116
- export type RequireOnlyTypedId<T> = T extends { _id?: infer U; }
117
- ? Required<{ _id: U }>
118
- : { _id: Types.ObjectId };
119
-
120
119
  export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ? Require_id<DocType> : (Document<unknown, any, DocType> & Require_id<DocType> & TVirtuals & TMethodsAndOverrides);
121
120
 
122
121
  export interface TagSet {
@@ -196,7 +195,7 @@ declare module 'mongoose' {
196
195
  /** Returns a copy of this schema */
197
196
  clone<T = this>(): T;
198
197
 
199
- discriminator<T extends Schema = Schema>(name: string, schema: T): DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T>;
198
+ discriminator<T = Schema>(name: string, schema: T): DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, T>;
200
199
 
201
200
  /** Returns a new schema that has the picked `paths` from this schema. */
202
201
  pick<T = this>(paths: string[], options?: SchemaOptions): T;
@@ -257,8 +256,8 @@ declare module 'mongoose' {
257
256
  /** Defines a post hook for the model. */
258
257
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T>): this;
259
258
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
260
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
261
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
259
+ post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
260
+ post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
262
261
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
263
262
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
264
263
  post<T = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T, T>): this;
@@ -266,8 +265,8 @@ declare module 'mongoose' {
266
265
 
267
266
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
268
267
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
269
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
270
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
268
+ post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
269
+ post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
271
270
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
272
271
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
273
272
  post<T = M>(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
@@ -278,9 +277,8 @@ declare module 'mongoose' {
278
277
  pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction<T>): this;
279
278
  pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
280
279
  pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
281
- pre<T extends Query<any, any>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
282
- pre<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PreMiddlewareFunction<T>): this;
283
- pre<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
280
+ pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
281
+ pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
284
282
  pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
285
283
  pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
286
284
  pre<T = M>(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
@@ -452,10 +450,6 @@ declare module 'mongoose' {
452
450
 
453
451
  export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
454
452
 
455
- type Mutable<T> = {
456
- -readonly [K in keyof T]: T[K];
457
- };
458
-
459
453
  type _UpdateQuery<TSchema> = {
460
454
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
461
455
  $currentDate?: AnyKeys<TSchema> & AnyObject;
@@ -469,7 +463,7 @@ declare module 'mongoose' {
469
463
  $unset?: AnyKeys<TSchema> & AnyObject;
470
464
 
471
465
  /** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
472
- $addToSet?: Mutable<mongodb.SetFields<TSchema>>;
466
+ $addToSet?: AnyKeys<TSchema> & AnyObject;
473
467
  $pop?: AnyKeys<TSchema> & AnyObject;
474
468
  $pull?: AnyKeys<TSchema> & AnyObject;
475
469
  $push?: AnyKeys<TSchema> & AnyObject;
@@ -487,13 +481,6 @@ declare module 'mongoose' {
487
481
  { $replaceRoot: any } |
488
482
  { $replaceWith: any };
489
483
 
490
- export type __UpdateDefProperty<T> =
491
- [Extract<T, mongodb.ObjectId>] extends [never] ? T :
492
- T | string;
493
- export type _UpdateQueryDef<T> = {
494
- [K in keyof T]?: __UpdateDefProperty<T[K]>;
495
- };
496
-
497
484
  /**
498
485
  * Update query command to perform on the document
499
486
  * @example
@@ -501,7 +488,7 @@ declare module 'mongoose' {
501
488
  * { age: 30 }
502
489
  * ```
503
490
  */
504
- export type UpdateQuery<T> = _UpdateQuery<_UpdateQueryDef<T>> & AnyObject;
491
+ export type UpdateQuery<T> = _UpdateQuery<T> & AnyObject;
505
492
 
506
493
  export type DocumentDefinition<T> = {
507
494
  [K in keyof Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>>]:
@@ -527,7 +514,6 @@ declare module 'mongoose' {
527
514
  T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> :
528
515
  LeanDocument<T>; // Documents and everything else
529
516
 
530
-
531
517
  export type LeanArray<T extends unknown[]> = T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
532
518
 
533
519
  export type _LeanDocument<T> = {
package/types/models.d.ts CHANGED
@@ -113,6 +113,8 @@ declare module 'mongoose' {
113
113
  wtimeout?: number;
114
114
  }
115
115
 
116
+ interface RemoveOptions extends SessionOption, Omit<mongodb.DeleteOptions, 'session'> {}
117
+
116
118
  const Model: Model<any>;
117
119
  interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}, TSchema = any> extends
118
120
  NodeJS.EventEmitter,
@@ -260,21 +262,21 @@ declare module 'mongoose' {
260
262
  init(callback?: CallbackWithoutResult): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
261
263
 
262
264
  /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
263
- insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>): void;
265
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>): void;
264
266
  insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { rawResult: true; }, callback: Callback<mongodb.InsertManyResult<T>>): void;
265
- insertMany<DocContents = T>(docs: Array<DocContents | T>, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
266
- insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>): void;
267
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
268
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>): void;
267
269
  insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { rawResult: true; }, callback: Callback<mongodb.InsertManyResult<T>>): void;
268
- insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean?: false | undefined }, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
269
- insertMany<DocContents = T>(doc: DocContents, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
270
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean?: false | undefined }, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
271
+ insertMany<DocContents = T>(doc: DocContents, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
270
272
 
271
- insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>;
273
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>;
272
274
  insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { rawResult: true; }): Promise<mongodb.InsertManyResult<T>>;
273
- insertMany<DocContents = T>(docs: Array<DocContents | T>): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
274
- insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>;
275
+ insertMany<DocContents = T>(docs: Array<DocContents | T>): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>;
276
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, Require_id<T>>>>;
275
277
  insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { rawResult: true; }): Promise<mongodb.InsertManyResult<T>>;
276
- insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
277
- insertMany<DocContents = T>(doc: DocContents): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
278
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>;
279
+ insertMany<DocContents = T>(doc: DocContents): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, Require_id<T>>, TMethodsAndOverrides, TVirtuals>>>;
278
280
 
279
281
  /** The name of the model */
280
282
  modelName: string;
@@ -392,6 +394,7 @@ declare module 'mongoose' {
392
394
  ): Promise<any>;
393
395
 
394
396
  remove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
397
+ remove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: any, options?: RemoveOptions, callback?: CallbackWithoutResult): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
395
398
 
396
399
  /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
397
400
  replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
@@ -141,7 +141,7 @@ declare module 'mongoose' {
141
141
  localField?: string
142
142
  foreignField?: string
143
143
  let?: Record<string, any>
144
- pipeline?: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out | PipelineStage.Search>[]
144
+ pipeline?: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out>[]
145
145
  }
146
146
  }
147
147
 
package/types/query.d.ts CHANGED
@@ -271,7 +271,7 @@ declare module 'mongoose' {
271
271
  distinct<ReturnType = any>(field: string, filter?: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, DocType, THelpers, RawDocType>;
272
272
 
273
273
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
274
- elemMatch<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$elemMatch']): this;
274
+ elemMatch<K = string>(path: K, val: any): this;
275
275
  elemMatch(val: Function | any): this;
276
276
 
277
277
  /**
@@ -288,7 +288,7 @@ declare module 'mongoose' {
288
288
  estimatedDocumentCount(options?: QueryOptions<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
289
289
 
290
290
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
291
- exists<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$exists']): this;
291
+ exists<K = string>(path: K, val: boolean): this;
292
292
  exists(val: boolean): this;
293
293
 
294
294
  /**
@@ -368,6 +368,23 @@ declare module 'mongoose' {
368
368
  callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
369
369
  ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
370
370
 
371
+ /** Declares the query a findById operation. When executed, the document with the given `_id` is passed to the callback. */
372
+ findById(
373
+ id: mongodb.ObjectId | any,
374
+ projection?: ProjectionType<DocType> | null,
375
+ options?: QueryOptions<DocType> | null,
376
+ callback?: Callback<DocType | null>
377
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
378
+ findById(
379
+ id: mongodb.ObjectId | any,
380
+ projection?: ProjectionType<DocType> | null,
381
+ callback?: Callback<DocType | null>
382
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
383
+ findById(
384
+ id: mongodb.ObjectId | any,
385
+ callback?: Callback<DocType | null>
386
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
387
+
371
388
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
372
389
  findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions<DocType> | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
373
390
 
@@ -403,18 +420,18 @@ declare module 'mongoose' {
403
420
  getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
404
421
 
405
422
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
406
- gt<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$gt']): this;
423
+ gt<K = string>(path: K, val: any): this;
407
424
  gt(val: number): this;
408
425
 
409
426
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
410
- gte<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$gte']): this;
427
+ gte<K = string>(path: K, val: any): this;
411
428
  gte(val: number): this;
412
429
 
413
430
  /** Sets query hints. */
414
431
  hint(val: any): this;
415
432
 
416
433
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
417
- in<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$in']): this;
434
+ in<K = string>(path: K, val: any[]): this;
418
435
  in(val: Array<any>): this;
419
436
 
420
437
  /** Declares an intersects query for `geometry()`. */
@@ -430,11 +447,11 @@ declare module 'mongoose' {
430
447
  limit(val: number): this;
431
448
 
432
449
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
433
- lt<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$lt']): this;
450
+ lt<K = string>(path: K, val: any): this;
434
451
  lt(val: number): this;
435
452
 
436
453
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
437
- lte<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$lte']): this;
454
+ lte<K = string>(path: K, val: any): this;
438
455
  lte(val: number): this;
439
456
 
440
457
  /**
@@ -461,7 +478,7 @@ declare module 'mongoose' {
461
478
  merge(source: Query<any, any> | FilterQuery<DocType>): this;
462
479
 
463
480
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
464
- mod<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$mod']): this;
481
+ mod<K = string>(path: K, val: number): this;
465
482
  mod(val: Array<number>): this;
466
483
 
467
484
  /** The model this query was created from */
@@ -474,15 +491,15 @@ declare module 'mongoose' {
474
491
  mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
475
492
 
476
493
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
477
- ne<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$ne']): this;
494
+ ne<K = string>(path: K, val: any): this;
478
495
  ne(val: any): this;
479
496
 
480
497
  /** Specifies a `$near` or `$nearSphere` condition */
481
- near<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$near']): this;
498
+ near<K = string>(path: K, val: any): this;
482
499
  near(val: any): this;
483
500
 
484
501
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
485
- nin<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$nin']): this;
502
+ nin<K = string>(path: K, val: any[]): this;
486
503
  nin(val: Array<any>): this;
487
504
 
488
505
  /** Specifies arguments for an `$nor` condition. */
@@ -518,7 +535,7 @@ declare module 'mongoose' {
518
535
  readConcern(level: string): this;
519
536
 
520
537
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
521
- regex<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$regex']): this;
538
+ regex<K = string>(path: K, val: RegExp): this;
522
539
  regex(val: string | RegExp): this;
523
540
 
524
541
  /**
@@ -570,7 +587,7 @@ declare module 'mongoose' {
570
587
  setUpdate(update: UpdateQuery<DocType> | UpdateWithAggregationPipeline): void;
571
588
 
572
589
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
573
- size<K extends keyof FilterQuery<DocType>>(path: K, val: FilterQuery<DocType>[K]['$size']): this;
590
+ size<K = string>(path: K, val: number): this;
574
591
  size(val: number): this;
575
592
 
576
593
  /** Specifies the number of documents to skip. */
@@ -599,7 +616,7 @@ declare module 'mongoose' {
599
616
  then: Promise<ResultType>['then'];
600
617
 
601
618
  /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
602
- toConstructor(): new (...args: any[]) => QueryWithHelpers<ResultType, DocType, THelpers, RawDocType>;
619
+ toConstructor(): typeof this;
603
620
 
604
621
  /** Declare and/or execute this query as an update() operation. */
605
622
  update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;