mongoose 6.2.11 → 6.3.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.
Files changed (49) hide show
  1. package/.eslintrc.json +157 -157
  2. package/README.md +1 -1
  3. package/dist/browser.umd.js +2 -1704
  4. package/lib/aggregate.js +4 -3
  5. package/lib/collection.js +0 -7
  6. package/lib/connection.js +2 -1
  7. package/lib/cursor/ChangeStream.js +42 -2
  8. package/lib/cursor/QueryCursor.js +2 -0
  9. package/lib/document.js +22 -26
  10. package/lib/error/cast.js +8 -2
  11. package/lib/error/eachAsyncMultiError.js +41 -0
  12. package/lib/helpers/common.js +0 -8
  13. package/lib/helpers/cursor/eachAsync.js +44 -12
  14. package/lib/helpers/immediate.js +3 -1
  15. package/lib/helpers/isAsyncFunction.js +19 -7
  16. package/lib/helpers/model/discriminator.js +1 -3
  17. package/lib/helpers/populate/getModelsMapForPopulate.js +13 -10
  18. package/lib/helpers/query/applyGlobalOption.js +29 -0
  19. package/lib/helpers/schematype/handleImmutable.js +4 -1
  20. package/lib/helpers/timestamps/setupTimestamps.js +2 -2
  21. package/lib/index.js +11 -4
  22. package/lib/internal.js +0 -1
  23. package/lib/model.js +39 -27
  24. package/lib/query.js +23 -4
  25. package/lib/queryhelpers.js +11 -1
  26. package/lib/schema/SubdocumentPath.js +3 -15
  27. package/lib/schema/documentarray.js +7 -7
  28. package/lib/schema/number.js +1 -5
  29. package/lib/schema/objectid.js +2 -4
  30. package/lib/schema/string.js +1 -5
  31. package/lib/schema.js +115 -2
  32. package/lib/schematype.js +2 -2
  33. package/lib/types/DocumentArray/methods/index.js +9 -1
  34. package/lib/types/array/methods/index.js +8 -9
  35. package/lib/validoptions.js +1 -0
  36. package/package.json +25 -18
  37. package/tools/repl.js +2 -1
  38. package/tsconfig.json +2 -2
  39. package/types/aggregate.d.ts +1 -2
  40. package/types/connection.d.ts +4 -5
  41. package/types/cursor.d.ts +13 -6
  42. package/types/document.d.ts +17 -14
  43. package/types/error.d.ts +124 -124
  44. package/types/index.d.ts +350 -202
  45. package/types/mongooseoptions.d.ts +11 -6
  46. package/types/schemaoptions.d.ts +1 -2
  47. package/CHANGELOG.md +0 -7238
  48. package/History.md +0 -1
  49. package/lib/helpers/query/applyGlobalMaxTimeMS.js +0 -15
package/types/index.d.ts CHANGED
@@ -7,13 +7,12 @@
7
7
  /// <reference path="./pipelinestage.d.ts" />
8
8
  /// <reference path="./schemaoptions.d.ts" />
9
9
 
10
- import events = require('events');
11
- import mongodb = require('mongodb');
12
- import mongoose = require('mongoose');
10
+ declare class NativeDate extends global.Date { }
13
11
 
14
12
  declare module 'mongoose' {
15
-
16
- class NativeDate extends global.Date {}
13
+ import events = require('events');
14
+ import mongodb = require('mongodb');
15
+ import mongoose = require('mongoose');
17
16
 
18
17
  /** The Mongoose Date [SchemaType](/docs/schematypes.html). */
19
18
  export type Date = Schema.Types.Date;
@@ -34,11 +33,13 @@ declare module 'mongoose' {
34
33
  */
35
34
  export type Mixed = Schema.Types.Mixed;
36
35
 
36
+ export type Mongoose = typeof mongoose;
37
+
37
38
  /**
38
39
  * Mongoose constructor. The exports object of the `mongoose` module is an instance of this
39
40
  * class. Most apps will only use this one instance.
40
41
  */
41
- export const Mongoose: new (options?: MongooseOptions | null) => typeof mongoose;
42
+ export const Mongoose: new (options?: MongooseOptions | null) => Mongoose;
42
43
 
43
44
  /**
44
45
  * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
@@ -88,7 +89,7 @@ declare module 'mongoose' {
88
89
  /**
89
90
  * Can be extended to explicitly type specific models.
90
91
  */
91
- interface Models {
92
+ export interface Models {
92
93
  [modelName: string]: Model<any>
93
94
  }
94
95
 
@@ -105,7 +106,7 @@ declare module 'mongoose' {
105
106
  * You can use this function to clean up any models you created in your tests to
106
107
  * prevent OverwriteModelErrors.
107
108
  */
108
- export function deleteModel(name: string | RegExp): typeof mongoose;
109
+ export function deleteModel(name: string | RegExp): Mongoose;
109
110
 
110
111
  export function disconnect(): Promise<void>;
111
112
  export function disconnect(cb: CallbackWithoutResult): void;
@@ -114,7 +115,7 @@ declare module 'mongoose' {
114
115
  export function get<K extends keyof MongooseOptions>(key: K): MongooseOptions[K];
115
116
 
116
117
  /* ! ignore */
117
- type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection };
118
+ export type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection };
118
119
 
119
120
  /**
120
121
  * Returns true if Mongoose can cast the given value to an ObjectId, or
@@ -152,13 +153,13 @@ declare module 'mongoose' {
152
153
  export function now(): NativeDate;
153
154
 
154
155
  /** Declares a global plugin executed on all Schemas. */
155
- export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): typeof mongoose;
156
+ export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose;
156
157
 
157
158
  /** Getter/setter around function for pluralizing collection names. */
158
159
  export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null;
159
160
 
160
161
  /** Sets mongoose options */
161
- export function set<K extends keyof MongooseOptions>(key: K, value: MongooseOptions[K]): typeof mongoose;
162
+ export function set<K extends keyof MongooseOptions>(key: K, value: MongooseOptions[K]): Mongoose;
162
163
 
163
164
  /**
164
165
  * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
@@ -174,16 +175,13 @@ declare module 'mongoose' {
174
175
  export type CastError = Error.CastError;
175
176
  export type SyncIndexesError = Error.SyncIndexesError;
176
177
 
177
- type Mongoose = typeof mongoose;
178
-
179
- // eslint-disable-next-line @typescript-eslint/no-empty-interface
180
- interface ClientSession extends mongodb.ClientSession { }
178
+ export type ClientSession = mongodb.ClientSession;
181
179
 
182
180
  /*
183
181
  * section collection.js
184
182
  * http://mongoosejs.com/docs/api.html#collection-js
185
183
  */
186
- interface CollectionBase<T> extends mongodb.Collection<T> {
184
+ export interface CollectionBase<T extends mongodb.Document> extends mongodb.Collection<T> {
187
185
  /*
188
186
  * Abstract methods. Some of these are already defined on the
189
187
  * mongodb.Collection interface so they've been commented out.
@@ -204,8 +202,8 @@ declare module 'mongoose' {
204
202
  * section drivers/node-mongodb-native/collection.js
205
203
  * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js
206
204
  */
207
- let Collection: Collection;
208
- interface Collection<T = AnyObject> extends CollectionBase<T> {
205
+ export let Collection: Collection;
206
+ export interface Collection<T extends mongodb.Document = mongodb.Document> extends CollectionBase<T> {
209
207
  /**
210
208
  * Collection constructor
211
209
  * @param name name of the collection
@@ -223,20 +221,19 @@ declare module 'mongoose' {
223
221
  }
224
222
 
225
223
  /** A list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. */
226
- type pathsToValidate = string[] | string;
224
+ export type pathsToValidate = string[] | string;
227
225
 
228
- interface AcceptsDiscriminator {
226
+ export interface AcceptsDiscriminator {
229
227
  /** Adds a discriminator type. */
230
228
  discriminator<D>(name: string | number, schema: Schema, value?: string | number | ObjectId): Model<D>;
231
229
  discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string | number | ObjectId): U;
232
230
  }
233
231
 
234
- type AnyKeys<T> = { [P in keyof T]?: T[P] | any };
235
- interface AnyObject {
232
+ export type AnyKeys<T> = { [P in keyof T]?: T[P] | any };
233
+ export interface AnyObject {
236
234
  [k: string]: any
237
235
  }
238
-
239
- type Require_id<T> = T extends { _id?: any } ? (T & { _id: T['_id'] }) : (T & { _id: Types.ObjectId });
236
+ export type Require_id<T> = T extends { _id?: any } ? (T & { _id: T['_id'] }) : (T & { _id: Types.ObjectId });
240
237
 
241
238
  export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ? Require_id<DocType> : (Document<unknown, any, DocType> & Require_id<DocType> & TVirtuals & TMethodsAndOverrides);
242
239
 
@@ -247,7 +244,7 @@ declare module 'mongoose' {
247
244
  toDrop: Array<any>
248
245
  }
249
246
 
250
- interface ModifyResult<T> {
247
+ export interface ModifyResult<T> {
251
248
  value: Require_id<T> | null;
252
249
  /** see https://www.mongodb.com/docs/manual/reference/command/findAndModify/#lasterrorobject */
253
250
  lastErrorObject?: {
@@ -258,14 +255,14 @@ declare module 'mongoose' {
258
255
  }
259
256
 
260
257
  export const Model: Model<any>;
261
- interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
262
- new<DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
258
+ export interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
259
+ new <DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
263
260
 
264
261
  aggregate<R = any>(pipeline?: PipelineStage[], options?: mongodb.AggregateOptions, callback?: Callback<R[]>): Aggregate<Array<R>>;
265
262
  aggregate<R = any>(pipeline: PipelineStage[], cb: Function): Aggregate<Array<R>>;
266
263
 
267
264
  /** Base Mongoose instance the model uses. */
268
- base: typeof mongoose;
265
+ base: Mongoose;
269
266
 
270
267
  /**
271
268
  * If this is a discriminator model, `baseModelName` is the name of
@@ -299,7 +296,7 @@ declare module 'mongoose' {
299
296
 
300
297
  /** Creates a `countDocuments` query: counts the number of documents that match `filter`. */
301
298
  countDocuments(callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
302
- countDocuments(filter: FilterQuery<T>, options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
299
+ countDocuments(filter: FilterQuery<T>, options?: QueryOptions<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
303
300
 
304
301
  /** Creates a new document or documents */
305
302
  create(docs: (AnyKeys<T> | AnyObject)[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
@@ -317,8 +314,8 @@ declare module 'mongoose' {
317
314
  * mongoose will not create the collection for the model until any documents are
318
315
  * created. Use this method to create the collection explicitly.
319
316
  */
320
- createCollection<T>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
321
- createCollection<T>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
317
+ createCollection<T extends mongodb.Document>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
318
+ createCollection<T extends mongodb.Document>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
322
319
 
323
320
  /**
324
321
  * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
@@ -335,7 +332,7 @@ declare module 'mongoose' {
335
332
  * Behaves like `remove()`, but deletes all documents that match `conditions`
336
333
  * regardless of the `single` option.
337
334
  */
338
- deleteMany(filter?: FilterQuery<T>, options?: QueryOptions, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
335
+ deleteMany(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
339
336
  deleteMany(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
340
337
  deleteMany(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
341
338
 
@@ -344,7 +341,7 @@ declare module 'mongoose' {
344
341
  * Behaves like `remove()`, but deletes at most one document regardless of the
345
342
  * `single` option.
346
343
  */
347
- deleteOne(filter?: FilterQuery<T>, options?: QueryOptions, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
344
+ deleteOne(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
348
345
  deleteOne(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
349
346
  deleteOne(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
350
347
 
@@ -366,10 +363,34 @@ declare module 'mongoose' {
366
363
  * equivalent to `findOne({ _id: id })`. If you want to query by a document's
367
364
  * `_id`, use `findById()` instead of `findOne()`.
368
365
  */
369
- findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: any, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc | null>): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
366
+ findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
367
+ id: any,
368
+ projection?: ProjectionType<T> | null,
369
+ options?: QueryOptions<T> | null,
370
+ callback?: Callback<ResultDoc | null>
371
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
372
+ findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
373
+ id: any,
374
+ projection?: ProjectionType<T> | null,
375
+ callback?: Callback<ResultDoc | null>
376
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
370
377
 
371
378
  /** Finds one document. */
372
- findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc | null>): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
379
+ findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
380
+ filter?: FilterQuery<T>,
381
+ projection?: ProjectionType<T> | null,
382
+ options?: QueryOptions<T> | null,
383
+ callback?: Callback<ResultDoc | null>
384
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
385
+ findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
386
+ filter?: FilterQuery<T>,
387
+ projection?: ProjectionType<T> | null,
388
+ callback?: Callback<ResultDoc | null>
389
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
390
+ findOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
391
+ filter?: FilterQuery<T>,
392
+ callback?: Callback<ResultDoc | null>
393
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
373
394
 
374
395
  /**
375
396
  * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
@@ -440,10 +461,10 @@ declare module 'mongoose' {
440
461
  /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
441
462
  validate(callback?: CallbackWithoutResult): Promise<void>;
442
463
  validate(optional: any, callback?: CallbackWithoutResult): Promise<void>;
443
- validate(optional: any, pathsToValidate: string[], callback?: CallbackWithoutResult): Promise<void>;
464
+ validate(optional: any, pathsToValidate: pathsToValidate, callback?: CallbackWithoutResult): Promise<void>;
444
465
 
445
466
  /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
446
- watch<ResultType = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
467
+ watch<ResultType extends mongodb.Document = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
447
468
 
448
469
  /** Adds a `$where` clause to this query */
449
470
  $where(argument: string | Function): QueryWithHelpers<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
@@ -458,7 +479,7 @@ declare module 'mongoose' {
458
479
  distinct<ReturnType = any>(field: string, filter?: FilterQuery<T>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
459
480
 
460
481
  /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
461
- estimatedDocumentCount(options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
482
+ estimatedDocumentCount(options?: QueryOptions<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
462
483
 
463
484
  /**
464
485
  * Returns a document with its `_id` if at least one document exists in the database that matches
@@ -469,37 +490,61 @@ declare module 'mongoose' {
469
490
 
470
491
  /** Creates a `find` query: gets a list of documents that match `filter`. */
471
492
  find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
493
+ find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
494
+ filter: FilterQuery<T>,
495
+ projection?: ProjectionType<T> | null,
496
+ callback?: Callback<ResultDoc[]>
497
+ ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
472
498
  find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
473
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
499
+ find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, projection?: ProjectionType<T> | null, options?: QueryOptions<T> | null, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
474
500
 
475
501
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
476
- findByIdAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
502
+ findByIdAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
477
503
 
478
504
  /** Creates a `findByIdAndRemove` query, filtering by the given `_id`. */
479
- findByIdAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
505
+ findByIdAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
480
506
 
481
507
  /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
482
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
483
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
484
- findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
508
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions<T> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
509
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
510
+ findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, update?: UpdateQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
485
511
  findByIdAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id: mongodb.ObjectId | any, update: UpdateQuery<T>, callback: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
486
512
 
487
513
  /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
488
- findOneAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
514
+ findOneAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
489
515
 
490
516
  /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
491
- findOneAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
517
+ findOneAndRemove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
492
518
 
493
519
  /** Creates a `findOneAndReplace` query: atomically finds the given document and replaces it with `replacement`. */
494
- findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
495
- findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
520
+ findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, replacement: T | AnyObject, options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
521
+ findOneAndReplace<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
496
522
 
497
523
  /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
498
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res: any) => void): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
499
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, update: UpdateQuery<T>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: ResultDoc, res: any) => void): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
500
- findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: T | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
501
-
502
- geoSearch<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, options?: GeoSearchOptions, callback?: Callback<Array<ResultDoc>>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
524
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
525
+ filter: FilterQuery<T>,
526
+ update: UpdateQuery<T>,
527
+ options: QueryOptions<T> & { rawResult: true },
528
+ callback?: (err: CallbackError, doc: any, res: any) => void
529
+ ): QueryWithHelpers<ModifyResult<ResultDoc>, ResultDoc, TQueryHelpers, T>;
530
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
531
+ filter: FilterQuery<T>,
532
+ update: UpdateQuery<T>,
533
+ options: QueryOptions<T> & { upsert: true } & ReturnsNewDoc,
534
+ callback?: (err: CallbackError, doc: ResultDoc, res: any) => void
535
+ ): QueryWithHelpers<ResultDoc, ResultDoc, TQueryHelpers, T>;
536
+ findOneAndUpdate<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
537
+ filter?: FilterQuery<T>,
538
+ update?: UpdateQuery<T>,
539
+ options?: QueryOptions<T> | null,
540
+ callback?: (err: CallbackError, doc: T | null, res: any) => void
541
+ ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
542
+
543
+ geoSearch<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
544
+ filter?: FilterQuery<T>,
545
+ options?: GeoSearchOptions,
546
+ callback?: Callback<Array<ResultDoc>>
547
+ ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
503
548
 
504
549
  /** Executes a mapReduce command. */
505
550
  mapReduce<Key, Value>(
@@ -510,8 +555,18 @@ declare module 'mongoose' {
510
555
  remove<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: any, callback?: CallbackWithoutResult): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
511
556
 
512
557
  /** Creates a `replaceOne` query: finds the first document that matches `filter` and replaces it with `replacement`. */
513
- replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
514
- replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, replacement?: T | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
558
+ replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
559
+ filter?: FilterQuery<T>,
560
+ replacement?: T | AnyObject,
561
+ options?: QueryOptions<T> | null,
562
+ callback?: Callback
563
+ ): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
564
+ replaceOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
565
+ filter?: FilterQuery<T>,
566
+ replacement?: T | AnyObject,
567
+ options?: QueryOptions<T> | null,
568
+ callback?: Callback
569
+ ): QueryWithHelpers<any, ResultDoc, TQueryHelpers, T>;
515
570
 
516
571
  /** Schema the model uses. */
517
572
  schema: Schema<T>;
@@ -520,13 +575,28 @@ declare module 'mongoose' {
520
575
  * @deprecated use `updateOne` or `updateMany` instead.
521
576
  * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
522
577
  */
523
- update<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
578
+ update<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
579
+ filter?: FilterQuery<T>,
580
+ update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
581
+ options?: QueryOptions<T> | null,
582
+ callback?: Callback
583
+ ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
524
584
 
525
585
  /** Creates a `updateMany` query: updates all documents that match `filter` with `update`. */
526
- updateMany<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
586
+ updateMany<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
587
+ filter?: FilterQuery<T>,
588
+ update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
589
+ options?: QueryOptions<T> | null,
590
+ callback?: Callback
591
+ ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
527
592
 
528
593
  /** Creates a `updateOne` query: updates the first document that matches `filter` with `update`. */
529
- updateOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter?: FilterQuery<T>, update?: UpdateQuery<T> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
594
+ updateOne<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
595
+ filter?: FilterQuery<T>,
596
+ update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
597
+ options?: QueryOptions<T> | null,
598
+ callback?: Callback
599
+ ): QueryWithHelpers<UpdateWriteOpResult, ResultDoc, TQueryHelpers, T>;
530
600
 
531
601
  /** Creates a Query, applies the passed conditions, and returns the Query. */
532
602
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(path: string, val?: any): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
@@ -534,9 +604,9 @@ declare module 'mongoose' {
534
604
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
535
605
  }
536
606
 
537
- type UpdateWriteOpResult = mongodb.UpdateResult;
607
+ export type UpdateWriteOpResult = mongodb.UpdateResult;
538
608
 
539
- interface QueryOptions {
609
+ export interface QueryOptions<DocType = unknown> {
540
610
  arrayFilters?: { [key: string]: any }[];
541
611
  batchSize?: number;
542
612
  collation?: mongodb.CollationOptions;
@@ -563,7 +633,7 @@ declare module 'mongoose' {
563
633
  overwrite?: boolean;
564
634
  overwriteDiscriminatorKey?: boolean;
565
635
  populate?: string | string[] | PopulateOptions | PopulateOptions[];
566
- projection?: any;
636
+ projection?: ProjectionType<DocType>;
567
637
  /**
568
638
  * if true, returns the raw result from the MongoDB driver
569
639
  */
@@ -611,9 +681,9 @@ declare module 'mongoose' {
611
681
  [other: string]: any;
612
682
  }
613
683
 
614
- type MongooseQueryOptions = Pick<QueryOptions, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
684
+ export type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
615
685
 
616
- interface SaveOptions {
686
+ export interface SaveOptions {
617
687
  checkKeys?: boolean;
618
688
  j?: boolean;
619
689
  safe?: boolean | WriteConcern;
@@ -625,17 +695,17 @@ declare module 'mongoose' {
625
695
  wtimeout?: number;
626
696
  }
627
697
 
628
- interface WriteConcern {
698
+ export interface WriteConcern {
629
699
  j?: boolean;
630
700
  w?: number | 'majority' | TagSet;
631
701
  wtimeout?: number;
632
702
  }
633
703
 
634
- interface TagSet {
704
+ export interface TagSet {
635
705
  [k: string]: string;
636
706
  }
637
707
 
638
- interface InsertManyOptions {
708
+ export interface InsertManyOptions {
639
709
  limit?: number;
640
710
  rawResult?: boolean;
641
711
  ordered?: boolean;
@@ -644,15 +714,15 @@ declare module 'mongoose' {
644
714
  populate?: string | string[] | PopulateOptions | PopulateOptions[];
645
715
  }
646
716
 
647
- type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
648
- type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
717
+ export type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
718
+ export type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
649
719
  insertedIds: {
650
720
  [key: number]: InferIdType<T>;
651
721
  };
652
722
  mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> };
653
723
  };
654
724
 
655
- interface MapReduceOptions<T, Key, Val> {
725
+ export interface MapReduceOptions<T, Key, Val> {
656
726
  map: Function | string;
657
727
  reduce: (key: Key, vals: T[]) => Val;
658
728
  /** query filter object. */
@@ -694,7 +764,7 @@ declare module 'mongoose' {
694
764
  };
695
765
  }
696
766
 
697
- interface GeoSearchOptions {
767
+ export interface GeoSearchOptions {
698
768
  /** x,y point to search for */
699
769
  near: number[];
700
770
  /** the maximum distance from the point near that a result can be */
@@ -705,7 +775,7 @@ declare module 'mongoose' {
705
775
  lean?: boolean;
706
776
  }
707
777
 
708
- interface PopulateOptions {
778
+ export interface PopulateOptions {
709
779
  /** space delimited path(s) to populate */
710
780
  path: string;
711
781
  /** fields to select */
@@ -716,6 +786,8 @@ declare module 'mongoose' {
716
786
  model?: string | Model<any>;
717
787
  /** optional query options like sort, limit, etc */
718
788
  options?: any;
789
+ /** correct limit on populated array */
790
+ perDocumentLimit?: number;
719
791
  /** optional boolean, set to `false` to allow populating paths that aren't in the schema */
720
792
  strictPopulate?: boolean;
721
793
  /** deep populate */
@@ -729,7 +801,7 @@ declare module 'mongoose' {
729
801
  transform?: (doc: any, id: any) => any;
730
802
  }
731
803
 
732
- interface ToObjectOptions {
804
+ export interface ToObjectOptions {
733
805
  /** apply all getters (path and virtual getters) */
734
806
  getters?: boolean;
735
807
  /** apply virtual getters (can override getters option) */
@@ -750,21 +822,21 @@ declare module 'mongoose' {
750
822
  useProjection?: boolean;
751
823
  }
752
824
 
753
- type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
754
- type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
825
+ export type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
826
+ export type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
755
827
 
756
- type SchemaPreOptions = { document?: boolean, query?: boolean };
757
- type SchemaPostOptions = { document?: boolean, query?: boolean };
828
+ export type SchemaPreOptions = { document?: boolean, query?: boolean };
829
+ export type SchemaPostOptions = { document?: boolean, query?: boolean };
758
830
 
759
- type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
760
- type IndexDefinition = Record<string, IndexDirection>;
831
+ export type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
832
+ export type IndexDefinition = Record<string, IndexDirection>;
761
833
 
762
834
  export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
763
835
  export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
764
836
  export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
765
837
  export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
766
838
 
767
- class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}> extends events.EventEmitter {
839
+ export class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}> extends events.EventEmitter {
768
840
  /**
769
841
  * Create a new schema
770
842
  */
@@ -780,6 +852,9 @@ declare module 'mongoose' {
780
852
  */
781
853
  childSchemas: { schema: Schema, model: any }[];
782
854
 
855
+ /** Removes all indexes on this schema */
856
+ clearIndexes(): this;
857
+
783
858
  /** Returns a copy of this schema */
784
859
  clone<T = this>(): T;
785
860
 
@@ -879,6 +954,9 @@ declare module 'mongoose' {
879
954
  /** Removes the given `path` (or [`paths`]). */
880
955
  remove(paths: string | Array<string>): this;
881
956
 
957
+ /** Removes index by name or index spec */
958
+ remove(index: string | AnyObject): this;
959
+
882
960
  /** Returns an Array of path strings that are required by this schema. */
883
961
  requiredPaths(invalidate?: boolean): string[];
884
962
 
@@ -893,22 +971,25 @@ declare module 'mongoose' {
893
971
  statics: { [name: string]: (this: M, ...args: any[]) => any };
894
972
 
895
973
  /** Creates a virtual type with the given name. */
896
- virtual<T = HydratedDocument<DocType, TInstanceMethods>>(name: string, options?: VirtualTypeOptions<T>): VirtualType;
974
+ virtual<T = HydratedDocument<DocType, TInstanceMethods>>(
975
+ name: string,
976
+ options?: VirtualTypeOptions<T, DocType>
977
+ ): VirtualType<T>;
897
978
 
898
979
  /** Object of currently defined virtuals on this schema */
899
980
  virtuals: any;
900
981
 
901
982
  /** Returns the virtual type with the given `name`. */
902
- virtualpath(name: string): VirtualType | null;
983
+ virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
903
984
  }
904
985
 
905
- type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
906
- type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
907
- type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
908
- type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
909
- type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
986
+ export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
987
+ export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
988
+ export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
989
+ export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
990
+ export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
910
991
 
911
- type SchemaDefinitionWithBuiltInClass<T> = T extends number
992
+ export type SchemaDefinitionWithBuiltInClass<T> = T extends number
912
993
  ? NumberSchemaDefinition
913
994
  : T extends string
914
995
  ? StringSchemaDefinition
@@ -918,7 +999,7 @@ declare module 'mongoose' {
918
999
  ? DateSchemaDefinition
919
1000
  : (Function | string);
920
1001
 
921
- type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1002
+ export type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
922
1003
  SchemaTypeOptions<T extends undefined ? any : T> |
923
1004
  typeof SchemaType |
924
1005
  Schema<any, any, any> |
@@ -930,24 +1011,24 @@ declare module 'mongoose' {
930
1011
  typeof Schema.Types.Mixed |
931
1012
  MixedSchemaTypeOptions;
932
1013
 
933
- type SchemaDefinition<T = undefined> = T extends undefined
1014
+ export type SchemaDefinition<T = undefined> = T extends undefined
934
1015
  ? { [path: string]: SchemaDefinitionProperty; }
935
1016
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
936
1017
 
937
- type Unpacked<T> = T extends (infer U)[] ?
1018
+ export type Unpacked<T> = T extends (infer U)[] ?
938
1019
  U :
939
1020
  T extends ReadonlyArray<infer U> ? U : T;
940
1021
 
941
- type AnyArray<T> = T[] | ReadonlyArray<T>;
942
- type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1022
+ export type AnyArray<T> = T[] | ReadonlyArray<T>;
1023
+ export type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
943
1024
 
944
- type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
1025
+ export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
945
1026
 
946
- class MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1027
+ export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
947
1028
  type: typeof Schema.Types.Mixed;
948
1029
  }
949
1030
 
950
- export class SchemaTypeOptions<T> {
1031
+ export interface SchemaTypeOptions<T> {
951
1032
  type?:
952
1033
  T extends string ? StringSchemaDefinition :
953
1034
  T extends number ? NumberSchemaDefinition :
@@ -1036,7 +1117,7 @@ declare module 'mongoose' {
1036
1117
  transform?: (this: any, val: T) => any;
1037
1118
 
1038
1119
  /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
1039
- get?: (value: T, doc?: this) => any;
1120
+ get?: (value: any, doc?: this) => T;
1040
1121
 
1041
1122
  /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
1042
1123
  set?: (value: any, priorVal?: T, doc?: this) => any;
@@ -1094,22 +1175,22 @@ declare module 'mongoose' {
1094
1175
  | string
1095
1176
  | Buffer
1096
1177
  | undefined
1097
- | mongoose.Types.ObjectId
1098
- | mongoose.Types.Buffer
1099
- | typeof mongoose.Schema.Types.Number
1100
- | typeof mongoose.Schema.Types.String
1101
- | typeof mongoose.Schema.Types.Buffer
1102
- | typeof mongoose.Schema.Types.ObjectId;
1178
+ | Types.ObjectId
1179
+ | Types.Buffer
1180
+ | typeof Schema.Types.Number
1181
+ | typeof Schema.Types.String
1182
+ | typeof Schema.Types.Buffer
1183
+ | typeof Schema.Types.ObjectId;
1103
1184
 
1104
1185
  /**
1105
1186
  * Reference another Model
1106
1187
  */
1107
1188
  export type PopulatedDoc<
1108
1189
  PopulatedType,
1109
- RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined
1190
+ RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : Types.ObjectId) | undefined
1110
1191
  > = PopulatedType | RawId;
1111
1192
 
1112
- interface IndexOptions extends mongodb.CreateIndexesOptions {
1193
+ export interface IndexOptions extends mongodb.CreateIndexesOptions {
1113
1194
  /**
1114
1195
  * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
1115
1196
  *
@@ -1134,37 +1215,37 @@ declare module 'mongoose' {
1134
1215
  weights?: AnyObject;
1135
1216
  }
1136
1217
 
1137
- interface ValidatorProps {
1218
+ export interface ValidatorProps {
1138
1219
  path: string;
1139
1220
  value: any;
1140
1221
  }
1141
1222
 
1142
- interface ValidatorMessageFn {
1223
+ export interface ValidatorMessageFn {
1143
1224
  (props: ValidatorProps): string;
1144
1225
  }
1145
1226
 
1146
- interface ValidateFn<T> {
1227
+ export interface ValidateFn<T> {
1147
1228
  (value: T): boolean;
1148
1229
  }
1149
1230
 
1150
- interface LegacyAsyncValidateFn<T> {
1231
+ export interface LegacyAsyncValidateFn<T> {
1151
1232
  (value: T, done: (result: boolean) => void): void;
1152
1233
  }
1153
1234
 
1154
- interface AsyncValidateFn<T> {
1235
+ export interface AsyncValidateFn<T> {
1155
1236
  (value: any): Promise<boolean>;
1156
1237
  }
1157
1238
 
1158
- interface ValidateOpts<T> {
1239
+ export interface ValidateOpts<T> {
1159
1240
  msg?: string;
1160
1241
  message?: string | ValidatorMessageFn;
1161
1242
  type?: string;
1162
1243
  validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
1163
1244
  }
1164
1245
 
1165
- type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1246
+ export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1166
1247
 
1167
- interface VirtualTypeOptions<HydratedDocType = Document> {
1248
+ export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1168
1249
  /** If `ref` is not nullish, this becomes a populated virtual. */
1169
1250
  ref?: string | Function;
1170
1251
 
@@ -1208,13 +1289,13 @@ declare module 'mongoose' {
1208
1289
  perDocumentLimit?: number;
1209
1290
 
1210
1291
  /** Additional options like `limit` and `lean`. */
1211
- options?: QueryOptions & { match?: AnyObject };
1292
+ options?: QueryOptions<DocType> & { match?: AnyObject };
1212
1293
 
1213
1294
  /** Additional options for plugins */
1214
1295
  [extra: string]: any;
1215
1296
  }
1216
1297
 
1217
- class VirtualType {
1298
+ export class VirtualType<HydratedDocType> {
1218
1299
  /** Applies getters to `value`. */
1219
1300
  applyGetters(value: any, doc: Document): any;
1220
1301
 
@@ -1222,13 +1303,13 @@ declare module 'mongoose' {
1222
1303
  applySetters(value: any, doc: Document): any;
1223
1304
 
1224
1305
  /** Adds a custom getter to this virtual. */
1225
- get(fn: Function): this;
1306
+ get<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => any): this;
1226
1307
 
1227
1308
  /** Adds a custom setter to this virtual. */
1228
- set(fn: Function): this;
1309
+ set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
1229
1310
  }
1230
1311
 
1231
- namespace Schema {
1312
+ export namespace Schema {
1232
1313
  namespace Types {
1233
1314
  class Array extends SchemaType implements AcceptsDiscriminator {
1234
1315
  /** This schema type's name, to defend against minifiers that mangle function names. */
@@ -1377,7 +1458,7 @@ declare module 'mongoose' {
1377
1458
  }
1378
1459
  }
1379
1460
 
1380
- namespace Types {
1461
+ export namespace Types {
1381
1462
  class Array<T> extends global.Array<T> {
1382
1463
  /** Pops the array atomically at most one time per document `save()`. */
1383
1464
  $pop(): T;
@@ -1475,20 +1556,20 @@ declare module 'mongoose' {
1475
1556
  }
1476
1557
  }
1477
1558
 
1478
- type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1559
+ export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1479
1560
 
1480
- type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1561
+ export type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1481
1562
 
1482
- type UnpackedIntersection<T, U> = T extends null ? null : T extends (infer A)[]
1563
+ export type UnpackedIntersection<T, U> = T extends null ? null : T extends (infer A)[]
1483
1564
  ? (Omit<A, keyof U> & U)[]
1484
1565
  : keyof U extends never
1485
1566
  ? T
1486
1567
  : Omit<T, keyof U> & U;
1487
1568
 
1488
- type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
1569
+ export type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
1489
1570
 
1490
- class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1491
- _mongooseOptions: MongooseQueryOptions;
1571
+ export class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1572
+ _mongooseOptions: MongooseQueryOptions<DocType>;
1492
1573
 
1493
1574
  /**
1494
1575
  * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
@@ -1557,20 +1638,24 @@ declare module 'mongoose' {
1557
1638
 
1558
1639
  /** Specifies this query as a `countDocuments` query. */
1559
1640
  countDocuments(callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1560
- countDocuments(criteria: FilterQuery<DocType>, options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1641
+ countDocuments(
1642
+ criteria: FilterQuery<DocType>,
1643
+ options?: QueryOptions<DocType>,
1644
+ callback?: Callback<number>
1645
+ ): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1561
1646
 
1562
1647
  /**
1563
1648
  * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html).
1564
1649
  * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
1565
1650
  */
1566
- cursor(options?: QueryOptions): Cursor<DocType, QueryOptions>;
1651
+ cursor(options?: QueryOptions<DocType>): Cursor<DocType, QueryOptions<DocType>>;
1567
1652
 
1568
1653
  /**
1569
1654
  * Declare and/or execute this query as a `deleteMany()` operation. Works like
1570
1655
  * remove, except it deletes _every_ document that matches `filter` in the
1571
1656
  * collection, regardless of the value of `single`.
1572
1657
  */
1573
- deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1658
+ deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1574
1659
  deleteMany(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1575
1660
  deleteMany(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1576
1661
 
@@ -1579,7 +1664,7 @@ declare module 'mongoose' {
1579
1664
  * remove, except it deletes at most one document regardless of the `single`
1580
1665
  * option.
1581
1666
  */
1582
- deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1667
+ deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1583
1668
  deleteOne(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1584
1669
  deleteOne(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1585
1670
 
@@ -1588,7 +1673,7 @@ declare module 'mongoose' {
1588
1673
 
1589
1674
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1590
1675
  elemMatch(val: Function | any): this;
1591
- elemMatch(path: string, val: Function | any): this;
1676
+ elemMatch<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$elemMatch']): this;
1592
1677
 
1593
1678
  /**
1594
1679
  * Gets/sets the error flag on this query. If this flag is not null or
@@ -1601,11 +1686,11 @@ declare module 'mongoose' {
1601
1686
  equals(val: any): this;
1602
1687
 
1603
1688
  /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
1604
- estimatedDocumentCount(options?: QueryOptions, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1689
+ estimatedDocumentCount(options?: QueryOptions<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
1605
1690
 
1606
1691
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1607
1692
  exists(val: boolean): this;
1608
- exists(path: string, val: boolean): this;
1693
+ exists<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$exists']): this;
1609
1694
 
1610
1695
  /**
1611
1696
  * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
@@ -1617,45 +1702,80 @@ declare module 'mongoose' {
1617
1702
 
1618
1703
  /** Creates a `find` query: gets a list of documents that match `filter`. */
1619
1704
  find(callback?: Callback<DocType[]>): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1620
- find(filter: FilterQuery<DocType>, callback?: Callback<DocType[]>): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1621
- find(filter: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<DocType[]>): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1705
+ find(
1706
+ filter: FilterQuery<DocType>,
1707
+ callback?: Callback<DocType[]>
1708
+ ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1709
+ find(
1710
+ filter: FilterQuery<DocType>,
1711
+ projection?: ProjectionType<DocType> | null,
1712
+ callback?: Callback<DocType[]>
1713
+ ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1714
+ find(
1715
+ filter: FilterQuery<DocType>,
1716
+ projection?: ProjectionType<DocType> | null,
1717
+ options?: QueryOptions<DocType> | null,
1718
+ callback?: Callback<DocType[]>
1719
+ ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
1622
1720
 
1623
1721
  /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */
1624
- findOne(filter?: FilterQuery<DocType>, projection?: any | null, options?: QueryOptions | null, callback?: Callback<DocType | null>): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1722
+ findOne(
1723
+ filter?: FilterQuery<DocType>,
1724
+ projection?: ProjectionType<DocType> | null,
1725
+ options?: QueryOptions<DocType> | null,
1726
+ callback?: Callback<DocType | null>
1727
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1728
+ findOne(
1729
+ filter?: FilterQuery<DocType>,
1730
+ projection?: ProjectionType<DocType> | null,
1731
+ callback?: Callback<DocType | null>
1732
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1733
+ findOne(
1734
+ filter?: FilterQuery<DocType>,
1735
+ callback?: Callback<DocType | null>
1736
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1625
1737
 
1626
1738
  /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
1627
- findOneAndDelete(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1739
+ findOneAndDelete(
1740
+ filter?: FilterQuery<DocType>,
1741
+ options?: QueryOptions<DocType> | null,
1742
+ callback?: (err: CallbackError, doc: DocType | null, res: any) => void
1743
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1628
1744
 
1629
1745
  /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
1630
- findOneAndRemove(filter?: FilterQuery<DocType>, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1746
+ findOneAndRemove(
1747
+ filter?: FilterQuery<DocType>,
1748
+ options?: QueryOptions<DocType> | null,
1749
+ callback?: (err: CallbackError, doc: DocType | null, res: any) => void
1750
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1631
1751
 
1632
1752
  /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
1633
1753
  findOneAndUpdate(
1634
1754
  filter: FilterQuery<DocType>,
1635
1755
  update: UpdateQuery<DocType>,
1636
- options: QueryOptions & { rawResult: true },
1756
+ options: QueryOptions<DocType> & { rawResult: true },
1637
1757
  callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
1638
1758
  ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType>;
1639
1759
  findOneAndUpdate(
1640
1760
  filter: FilterQuery<DocType>,
1641
1761
  update: UpdateQuery<DocType>,
1642
- options: QueryOptions & { upsert: true } & ReturnsNewDoc,
1762
+ options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc,
1643
1763
  callback?: (err: CallbackError, doc: DocType, res: ModifyResult<DocType>) => void
1644
1764
  ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
1645
1765
  findOneAndUpdate(
1646
1766
  filter?: FilterQuery<DocType>,
1647
1767
  update?: UpdateQuery<DocType>,
1648
- options?: QueryOptions | null,
1768
+ options?: QueryOptions<DocType> | null,
1649
1769
  callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
1650
1770
  ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1651
1771
 
1652
1772
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
1653
- findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1773
+ findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions<DocType> | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1654
1774
 
1655
1775
  /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
1656
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions & { rawResult: true }, callback?: (err: CallbackError, doc: any, res?: any) => void): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1657
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res?: any) => void): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
1658
- findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<DocType>, options?: QueryOptions | null, callback?: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1776
+ findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res?: any) => void): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1777
+ findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res?: any) => void): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
1778
+ findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<DocType>, options?: QueryOptions<DocType> | null, callback?: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1659
1779
  findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, callback: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
1660
1780
 
1661
1781
  /** Specifies a `$geometry` condition */
@@ -1672,7 +1792,7 @@ declare module 'mongoose' {
1672
1792
  getFilter(): FilterQuery<DocType>;
1673
1793
 
1674
1794
  /** Gets query options. */
1675
- getOptions(): QueryOptions;
1795
+ getOptions(): QueryOptions<DocType>;
1676
1796
 
1677
1797
  /** Gets a list of paths to be populated by this query */
1678
1798
  getPopulatedPaths(): Array<string>;
@@ -1685,18 +1805,18 @@ declare module 'mongoose' {
1685
1805
 
1686
1806
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1687
1807
  gt(val: number): this;
1688
- gt(path: string, val: number): this;
1808
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gt']): this;
1689
1809
 
1690
1810
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1691
1811
  gte(val: number): this;
1692
- gte(path: string, val: number): this;
1812
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gte']): this;
1693
1813
 
1694
1814
  /** Sets query hints. */
1695
1815
  hint(val: any): this;
1696
1816
 
1697
1817
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1698
1818
  in(val: Array<any>): this;
1699
- in(path: string, val: Array<any>): this;
1819
+ in<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$in']): this;
1700
1820
 
1701
1821
  /** Declares an intersects query for `geometry()`. */
1702
1822
  intersects(arg?: any): this;
@@ -1712,11 +1832,11 @@ declare module 'mongoose' {
1712
1832
 
1713
1833
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1714
1834
  lt(val: number): this;
1715
- lt(path: string, val: number): this;
1835
+ lt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lt']): this;
1716
1836
 
1717
1837
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1718
1838
  lte(val: number): this;
1719
- lte(path: string, val: number): this;
1839
+ lte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lte']): this;
1720
1840
 
1721
1841
  /**
1722
1842
  * Runs a function `fn` and treats the return value of `fn` as the new value
@@ -1743,7 +1863,7 @@ declare module 'mongoose' {
1743
1863
 
1744
1864
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
1745
1865
  mod(val: Array<number>): this;
1746
- mod(path: string, val: Array<number>): this;
1866
+ mod<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$mod']): this;
1747
1867
 
1748
1868
  /** The model this query was created from */
1749
1869
  model: typeof Model;
@@ -1756,15 +1876,15 @@ declare module 'mongoose' {
1756
1876
 
1757
1877
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1758
1878
  ne(val: any): this;
1759
- ne(path: string, val: any): this;
1879
+ ne<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$ne']): this;
1760
1880
 
1761
1881
  /** Specifies a `$near` or `$nearSphere` condition */
1762
1882
  near(val: any): this;
1763
- near(path: string, val: any): this;
1883
+ near<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$near']): this;
1764
1884
 
1765
1885
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1766
1886
  nin(val: Array<any>): this;
1767
- nin(path: string, val: Array<any>): this;
1887
+ nin<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$nin']): this;
1768
1888
 
1769
1889
  /** Specifies arguments for an `$nor` condition. */
1770
1890
  nor(array: Array<FilterQuery<DocType>>): this;
@@ -1800,7 +1920,7 @@ declare module 'mongoose' {
1800
1920
 
1801
1921
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1802
1922
  regex(val: string | RegExp): this;
1803
- regex(path: string, val: string | RegExp): this;
1923
+ regex<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$regex']): this;
1804
1924
 
1805
1925
  /**
1806
1926
  * Declare and/or execute this query as a remove() operation. `remove()` is
@@ -1814,8 +1934,8 @@ declare module 'mongoose' {
1814
1934
  * `update()`, except MongoDB will replace the existing document and will
1815
1935
  * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
1816
1936
  */
1817
- replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1818
- replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1937
+ replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions<DocType> | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1938
+ replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions<DocType> | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
1819
1939
 
1820
1940
  /** Specifies which document fields to include or exclude (also known as the query "projection") */
1821
1941
  select(arg: string | any): this;
@@ -1844,7 +1964,7 @@ declare module 'mongoose' {
1844
1964
  set(path: string | Record<string, unknown>, value?: any): this;
1845
1965
 
1846
1966
  /** Sets query options. Some options only make sense for certain operations. */
1847
- setOptions(options: QueryOptions, overwrite?: boolean): this;
1967
+ setOptions(options: QueryOptions<DocType>, overwrite?: boolean): this;
1848
1968
 
1849
1969
  /** Sets the query conditions to the provided JSON object. */
1850
1970
  setQuery(val: FilterQuery<DocType> | null): void;
@@ -1853,7 +1973,7 @@ declare module 'mongoose' {
1853
1973
 
1854
1974
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1855
1975
  size(val: number): this;
1856
- size(path: string, val: number): this;
1976
+ size<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$size']): this;
1857
1977
 
1858
1978
  /** Specifies the number of documents to skip. */
1859
1979
  skip(val: number): this;
@@ -1884,7 +2004,7 @@ declare module 'mongoose' {
1884
2004
  toConstructor(): new (...args: any[]) => QueryWithHelpers<ResultType, DocType, THelpers, RawDocType>;
1885
2005
 
1886
2006
  /** Declare and/or execute this query as an update() operation. */
1887
- update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2007
+ update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
1888
2008
 
1889
2009
  /**
1890
2010
  * Declare and/or execute this query as an updateMany() operation. Same as
@@ -1892,13 +2012,13 @@ declare module 'mongoose' {
1892
2012
  * `filter` (as opposed to just the first one) regardless of the value of
1893
2013
  * the `multi` option.
1894
2014
  */
1895
- updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2015
+ updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
1896
2016
 
1897
2017
  /**
1898
2018
  * Declare and/or execute this query as an updateOne() operation. Same as
1899
2019
  * `update()`, except it does not support the `multi` or `overwrite` options.
1900
2020
  */
1901
- updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
2021
+ updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
1902
2022
 
1903
2023
  /**
1904
2024
  * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,
@@ -1922,6 +2042,9 @@ declare module 'mongoose' {
1922
2042
  wtimeout(ms: number): this;
1923
2043
  }
1924
2044
 
2045
+ export type ProjectionElementType = number | string;
2046
+ export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
2047
+
1925
2048
  export type QuerySelector<T> = {
1926
2049
  // Comparison
1927
2050
  $eq?: T;
@@ -1989,10 +2112,10 @@ declare module 'mongoose' {
1989
2112
  [key: string]: any;
1990
2113
  };
1991
2114
 
1992
- type ApplyBasicQueryCasting<T> = T | T[] | any;
1993
- type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
2115
+ export type ApplyBasicQueryCasting<T> = T | T[] | any;
2116
+ export type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
1994
2117
 
1995
- type _FilterQuery<T> = {
2118
+ export type _FilterQuery<T> = {
1996
2119
  [P in keyof T]?: Condition<T[P]>;
1997
2120
  } &
1998
2121
  RootQuerySelector<T>;
@@ -2006,20 +2129,7 @@ declare module 'mongoose' {
2006
2129
  */
2007
2130
  export type FilterQuery<T> = _FilterQuery<T>;
2008
2131
 
2009
- type AddToSetOperators<Type> = {
2010
- $each: Type;
2011
- };
2012
-
2013
- type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2014
-
2015
- type ArrayOperator<Type> = {
2016
- $each: Type;
2017
- $slice?: number;
2018
- $position?: number;
2019
- $sort?: SortValues | Record<string, SortValues>;
2020
- };
2021
-
2022
- type NumericTypes = number | Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;
2132
+ export type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2023
2133
 
2024
2134
  type _UpdateQuery<TSchema> = {
2025
2135
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
@@ -2046,18 +2156,18 @@ declare module 'mongoose' {
2046
2156
  };
2047
2157
  };
2048
2158
 
2049
- type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2050
- type UpdateAggregationStage = { $addFields: any } |
2159
+ export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2160
+ export type UpdateAggregationStage = { $addFields: any } |
2051
2161
  { $set: any } |
2052
2162
  { $project: any } |
2053
2163
  { $unset: any } |
2054
2164
  { $replaceRoot: any } |
2055
2165
  { $replaceWith: any };
2056
2166
 
2057
- type __UpdateDefProperty<T> =
2167
+ export type __UpdateDefProperty<T> =
2058
2168
  [Extract<T, mongodb.ObjectId>] extends [never] ? T :
2059
2169
  T | string;
2060
- type _UpdateQueryDef<T> = {
2170
+ export type _UpdateQueryDef<T> = {
2061
2171
  [K in keyof T]?: __UpdateDefProperty<T[K]>;
2062
2172
  };
2063
2173
 
@@ -2085,17 +2195,27 @@ declare module 'mongoose' {
2085
2195
  ? T[K] : FlattenMaps<T[K]>;
2086
2196
  };
2087
2197
 
2088
- type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2089
- type TreatAsPrimitives = actualPrimitives |
2090
- NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
2198
+ export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2199
+ export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
2200
+
2201
+ // This will -- when possible -- extract the original type of the subdocument in question
2202
+ type LeanSubdocument<T> = T extends (Types.Subdocument<Require_id<T>['_id']> & infer U) ? LeanDocument<U> : Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'>;
2091
2203
 
2092
- type LeanType<T> =
2204
+ export type LeanType<T> =
2093
2205
  0 extends (1 & T) ? T : // any
2094
2206
  T extends TreatAsPrimitives ? T : // primitives
2095
- T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> : // subdocs
2207
+ T extends Types.Subdocument ? LeanSubdocument<T> : // subdocs
2096
2208
  LeanDocument<T>; // Documents and everything else
2097
2209
 
2098
- type LeanArray<T extends unknown[]> = T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
2210
+ // Used only when collapsing lean arrays for ts performance reasons:
2211
+ type LeanTypeOrArray<T> = T extends unknown[] ? LeanArray<T> : LeanType<T>;
2212
+
2213
+ export type LeanArray<T extends unknown[]> =
2214
+ // By checking if it extends Types.Array we can get the original base type before collapsing down,
2215
+ // rather than trying to manually remove the old types. This matches both Array and DocumentArray
2216
+ T extends Types.Array<infer U> ? LeanTypeOrArray<U>[] :
2217
+ // If it isn't a custom mongoose type we fall back to "do our best"
2218
+ T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
2099
2219
 
2100
2220
  export type _LeanDocument<T> = {
2101
2221
  [K in keyof T]: LeanDocumentElement<T[K]>;
@@ -2104,19 +2224,47 @@ declare module 'mongoose' {
2104
2224
  // Keep this a separate type, to ensure that T is a naked type.
2105
2225
  // This way, the conditional type is distributive over union types.
2106
2226
  // This is required for PopulatedDoc.
2107
- type LeanDocumentElement<T> =
2108
- T extends unknown[] ? LeanArray<T> : // Array
2109
- T extends Document ? LeanDocument<T> : // Subdocument
2110
- T;
2227
+ export type LeanDocumentElement<T> =
2228
+ 0 extends (1 & T) ? T :// any
2229
+ T extends unknown[] ? LeanArray<T> : // Array
2230
+ T extends Document ? LeanDocument<T> : // Subdocument
2231
+ T;
2111
2232
 
2112
2233
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
2113
2234
 
2235
+ // Helpers to simplify checks
2236
+ type IfAny<IFTYPE, THENTYPE> = 0 extends (1 & IFTYPE) ? THENTYPE : IFTYPE;
2237
+ type IfUnknown<IFTYPE, THENTYPE> = unknown extends IFTYPE ? THENTYPE : IFTYPE;
2238
+
2239
+ // tests for these two types are located in test/types/lean.test.ts
2240
+ export type DocTypeFromUnion<T> = T extends (Document<infer T1, infer T2, infer T3> & infer U) ?
2241
+ [U] extends [Document<T1, T2, T3> & infer U] ? IfUnknown<IfAny<U, false>, false> : false : false;
2242
+
2243
+ export type DocTypeFromGeneric<T> = T extends Document<infer IdType, infer TQueryHelpers, infer DocType> ?
2244
+ IfUnknown<IfAny<DocType, false>, false> : false;
2245
+
2246
+ /**
2247
+ * Helper to choose the best option between two type helpers
2248
+ */
2249
+ export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
2250
+
2251
+ /**
2252
+ * There may be a better way to do this, but the goal is to return the DocType if it can be infered
2253
+ * and if not to return a type which is easily identified as "not valid" so we fall back to
2254
+ * "strip out known things added by extending Document"
2255
+ * There are three basic ways to mix in Document -- "Document & T", "Document<ObjId, mixins, T>",
2256
+ * and "T extends Document". In the last case there is no type without Document mixins, so we can only
2257
+ * strip things out. In the other two cases we can infer the type, so we should
2258
+ */
2259
+ export type BaseDocumentType<T> = _pickObject<DocTypeFromUnion<T>, DocTypeFromGeneric<T>, false>;
2260
+
2114
2261
  /**
2115
2262
  * Documents returned from queries with the lean option enabled.
2116
2263
  * Plain old JavaScript object documents (POJO).
2117
2264
  * @see https://mongoosejs.com/docs/tutorials/lean.html
2118
2265
  */
2119
- export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
2266
+ export type LeanDocument<T> = BaseDocumentType<T> extends Document ? _LeanDocument<BaseDocumentType<T>> :
2267
+ Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
2120
2268
 
2121
2269
  export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
2122
2270
  T extends unknown[] ? LeanDocument<T[number]>[] :
@@ -2128,7 +2276,7 @@ declare module 'mongoose' {
2128
2276
  T extends Document ? RawDocType :
2129
2277
  T;
2130
2278
 
2131
- class SchemaType {
2279
+ export class SchemaType<T = any> {
2132
2280
  /** SchemaType constructor */
2133
2281
  constructor(path: string, options?: AnyObject, instance?: string);
2134
2282
 
@@ -2144,7 +2292,7 @@ declare module 'mongoose' {
2144
2292
  static get(getter: (value: any) => any): void;
2145
2293
 
2146
2294
  /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
2147
- OptionsConstructor: typeof SchemaTypeOptions;
2295
+ OptionsConstructor: SchemaTypeOptions<T>;
2148
2296
 
2149
2297
  /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
2150
2298
  cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
@@ -2221,14 +2369,14 @@ declare module 'mongoose' {
2221
2369
  continueOnError?: boolean
2222
2370
  }
2223
2371
  export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
2224
- type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2225
- type Callback<T = any> = (error: CallbackError, result: T) => void;
2372
+ export type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2373
+ export type Callback<T = any> = (error: CallbackError, result: T) => void;
2226
2374
 
2227
- type CallbackWithoutResult = (error: CallbackError) => void;
2228
- type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2375
+ export type CallbackWithoutResult = (error: CallbackError) => void;
2376
+ export type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2229
2377
 
2230
2378
  /* for ts-mongoose */
2231
- class mquery {}
2232
- }
2379
+ export class mquery { }
2233
2380
 
2234
- export default mongoose;
2381
+ export default mongoose;
2382
+ }