mongoose 6.3.1 → 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.
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.Document> 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 extends mongodb.Document = mongodb.Document> 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
@@ -464,7 +461,7 @@ declare module 'mongoose' {
464
461
  /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
465
462
  validate(callback?: CallbackWithoutResult): Promise<void>;
466
463
  validate(optional: any, callback?: CallbackWithoutResult): Promise<void>;
467
- validate(optional: any, pathsToValidate: string[], callback?: CallbackWithoutResult): Promise<void>;
464
+ validate(optional: any, pathsToValidate: pathsToValidate, callback?: CallbackWithoutResult): Promise<void>;
468
465
 
469
466
  /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
470
467
  watch<ResultType extends mongodb.Document = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
@@ -607,9 +604,9 @@ declare module 'mongoose' {
607
604
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
608
605
  }
609
606
 
610
- type UpdateWriteOpResult = mongodb.UpdateResult;
607
+ export type UpdateWriteOpResult = mongodb.UpdateResult;
611
608
 
612
- interface QueryOptions<DocType = unknown> {
609
+ export interface QueryOptions<DocType = unknown> {
613
610
  arrayFilters?: { [key: string]: any }[];
614
611
  batchSize?: number;
615
612
  collation?: mongodb.CollationOptions;
@@ -684,9 +681,9 @@ declare module 'mongoose' {
684
681
  [other: string]: any;
685
682
  }
686
683
 
687
- type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
684
+ export type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
688
685
 
689
- interface SaveOptions {
686
+ export interface SaveOptions {
690
687
  checkKeys?: boolean;
691
688
  j?: boolean;
692
689
  safe?: boolean | WriteConcern;
@@ -698,17 +695,17 @@ declare module 'mongoose' {
698
695
  wtimeout?: number;
699
696
  }
700
697
 
701
- interface WriteConcern {
698
+ export interface WriteConcern {
702
699
  j?: boolean;
703
700
  w?: number | 'majority' | TagSet;
704
701
  wtimeout?: number;
705
702
  }
706
703
 
707
- interface TagSet {
704
+ export interface TagSet {
708
705
  [k: string]: string;
709
706
  }
710
707
 
711
- interface InsertManyOptions {
708
+ export interface InsertManyOptions {
712
709
  limit?: number;
713
710
  rawResult?: boolean;
714
711
  ordered?: boolean;
@@ -717,15 +714,15 @@ declare module 'mongoose' {
717
714
  populate?: string | string[] | PopulateOptions | PopulateOptions[];
718
715
  }
719
716
 
720
- type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
721
- 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> & {
722
719
  insertedIds: {
723
720
  [key: number]: InferIdType<T>;
724
721
  };
725
722
  mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> };
726
723
  };
727
724
 
728
- interface MapReduceOptions<T, Key, Val> {
725
+ export interface MapReduceOptions<T, Key, Val> {
729
726
  map: Function | string;
730
727
  reduce: (key: Key, vals: T[]) => Val;
731
728
  /** query filter object. */
@@ -767,7 +764,7 @@ declare module 'mongoose' {
767
764
  };
768
765
  }
769
766
 
770
- interface GeoSearchOptions {
767
+ export interface GeoSearchOptions {
771
768
  /** x,y point to search for */
772
769
  near: number[];
773
770
  /** the maximum distance from the point near that a result can be */
@@ -778,7 +775,7 @@ declare module 'mongoose' {
778
775
  lean?: boolean;
779
776
  }
780
777
 
781
- interface PopulateOptions {
778
+ export interface PopulateOptions {
782
779
  /** space delimited path(s) to populate */
783
780
  path: string;
784
781
  /** fields to select */
@@ -804,7 +801,7 @@ declare module 'mongoose' {
804
801
  transform?: (doc: any, id: any) => any;
805
802
  }
806
803
 
807
- interface ToObjectOptions {
804
+ export interface ToObjectOptions {
808
805
  /** apply all getters (path and virtual getters) */
809
806
  getters?: boolean;
810
807
  /** apply virtual getters (can override getters option) */
@@ -825,21 +822,21 @@ declare module 'mongoose' {
825
822
  useProjection?: boolean;
826
823
  }
827
824
 
828
- type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
829
- 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';
830
827
 
831
- type SchemaPreOptions = { document?: boolean, query?: boolean };
832
- type SchemaPostOptions = { document?: boolean, query?: boolean };
828
+ export type SchemaPreOptions = { document?: boolean, query?: boolean };
829
+ export type SchemaPostOptions = { document?: boolean, query?: boolean };
833
830
 
834
- type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
835
- type IndexDefinition = Record<string, IndexDirection>;
831
+ export type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
832
+ export type IndexDefinition = Record<string, IndexDirection>;
836
833
 
837
834
  export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
838
835
  export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
839
836
  export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
840
837
  export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
841
838
 
842
- 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 {
843
840
  /**
844
841
  * Create a new schema
845
842
  */
@@ -986,13 +983,13 @@ declare module 'mongoose' {
986
983
  virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
987
984
  }
988
985
 
989
- type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
990
- type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
991
- type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
992
- type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
993
- 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;
994
991
 
995
- type SchemaDefinitionWithBuiltInClass<T> = T extends number
992
+ export type SchemaDefinitionWithBuiltInClass<T> = T extends number
996
993
  ? NumberSchemaDefinition
997
994
  : T extends string
998
995
  ? StringSchemaDefinition
@@ -1002,7 +999,7 @@ declare module 'mongoose' {
1002
999
  ? DateSchemaDefinition
1003
1000
  : (Function | string);
1004
1001
 
1005
- type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1002
+ export type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1006
1003
  SchemaTypeOptions<T extends undefined ? any : T> |
1007
1004
  typeof SchemaType |
1008
1005
  Schema<any, any, any> |
@@ -1014,24 +1011,24 @@ declare module 'mongoose' {
1014
1011
  typeof Schema.Types.Mixed |
1015
1012
  MixedSchemaTypeOptions;
1016
1013
 
1017
- type SchemaDefinition<T = undefined> = T extends undefined
1014
+ export type SchemaDefinition<T = undefined> = T extends undefined
1018
1015
  ? { [path: string]: SchemaDefinitionProperty; }
1019
1016
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
1020
1017
 
1021
- type Unpacked<T> = T extends (infer U)[] ?
1018
+ export type Unpacked<T> = T extends (infer U)[] ?
1022
1019
  U :
1023
1020
  T extends ReadonlyArray<infer U> ? U : T;
1024
1021
 
1025
- type AnyArray<T> = T[] | ReadonlyArray<T>;
1026
- 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>[];
1027
1024
 
1028
- 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;
1029
1026
 
1030
- class MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1027
+ export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1031
1028
  type: typeof Schema.Types.Mixed;
1032
1029
  }
1033
1030
 
1034
- export class SchemaTypeOptions<T> {
1031
+ export interface SchemaTypeOptions<T> {
1035
1032
  type?:
1036
1033
  T extends string ? StringSchemaDefinition :
1037
1034
  T extends number ? NumberSchemaDefinition :
@@ -1120,7 +1117,7 @@ declare module 'mongoose' {
1120
1117
  transform?: (this: any, val: T) => any;
1121
1118
 
1122
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). */
1123
- get?: (value: T, doc?: this) => any;
1120
+ get?: (value: any, doc?: this) => T;
1124
1121
 
1125
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). */
1126
1123
  set?: (value: any, priorVal?: T, doc?: this) => any;
@@ -1178,22 +1175,22 @@ declare module 'mongoose' {
1178
1175
  | string
1179
1176
  | Buffer
1180
1177
  | undefined
1181
- | mongoose.Types.ObjectId
1182
- | mongoose.Types.Buffer
1183
- | typeof mongoose.Schema.Types.Number
1184
- | typeof mongoose.Schema.Types.String
1185
- | typeof mongoose.Schema.Types.Buffer
1186
- | 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;
1187
1184
 
1188
1185
  /**
1189
1186
  * Reference another Model
1190
1187
  */
1191
1188
  export type PopulatedDoc<
1192
1189
  PopulatedType,
1193
- 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
1194
1191
  > = PopulatedType | RawId;
1195
1192
 
1196
- interface IndexOptions extends mongodb.CreateIndexesOptions {
1193
+ export interface IndexOptions extends mongodb.CreateIndexesOptions {
1197
1194
  /**
1198
1195
  * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
1199
1196
  *
@@ -1218,37 +1215,37 @@ declare module 'mongoose' {
1218
1215
  weights?: AnyObject;
1219
1216
  }
1220
1217
 
1221
- interface ValidatorProps {
1218
+ export interface ValidatorProps {
1222
1219
  path: string;
1223
1220
  value: any;
1224
1221
  }
1225
1222
 
1226
- interface ValidatorMessageFn {
1223
+ export interface ValidatorMessageFn {
1227
1224
  (props: ValidatorProps): string;
1228
1225
  }
1229
1226
 
1230
- interface ValidateFn<T> {
1227
+ export interface ValidateFn<T> {
1231
1228
  (value: T): boolean;
1232
1229
  }
1233
1230
 
1234
- interface LegacyAsyncValidateFn<T> {
1231
+ export interface LegacyAsyncValidateFn<T> {
1235
1232
  (value: T, done: (result: boolean) => void): void;
1236
1233
  }
1237
1234
 
1238
- interface AsyncValidateFn<T> {
1235
+ export interface AsyncValidateFn<T> {
1239
1236
  (value: any): Promise<boolean>;
1240
1237
  }
1241
1238
 
1242
- interface ValidateOpts<T> {
1239
+ export interface ValidateOpts<T> {
1243
1240
  msg?: string;
1244
1241
  message?: string | ValidatorMessageFn;
1245
1242
  type?: string;
1246
1243
  validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
1247
1244
  }
1248
1245
 
1249
- type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1246
+ export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1250
1247
 
1251
- interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1248
+ export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1252
1249
  /** If `ref` is not nullish, this becomes a populated virtual. */
1253
1250
  ref?: string | Function;
1254
1251
 
@@ -1298,7 +1295,7 @@ declare module 'mongoose' {
1298
1295
  [extra: string]: any;
1299
1296
  }
1300
1297
 
1301
- class VirtualType<HydratedDocType> {
1298
+ export class VirtualType<HydratedDocType> {
1302
1299
  /** Applies getters to `value`. */
1303
1300
  applyGetters(value: any, doc: Document): any;
1304
1301
 
@@ -1312,7 +1309,7 @@ declare module 'mongoose' {
1312
1309
  set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
1313
1310
  }
1314
1311
 
1315
- namespace Schema {
1312
+ export namespace Schema {
1316
1313
  namespace Types {
1317
1314
  class Array extends SchemaType implements AcceptsDiscriminator {
1318
1315
  /** This schema type's name, to defend against minifiers that mangle function names. */
@@ -1461,7 +1458,7 @@ declare module 'mongoose' {
1461
1458
  }
1462
1459
  }
1463
1460
 
1464
- namespace Types {
1461
+ export namespace Types {
1465
1462
  class Array<T> extends global.Array<T> {
1466
1463
  /** Pops the array atomically at most one time per document `save()`. */
1467
1464
  $pop(): T;
@@ -1559,19 +1556,19 @@ declare module 'mongoose' {
1559
1556
  }
1560
1557
  }
1561
1558
 
1562
- type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1559
+ export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1563
1560
 
1564
- 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;
1565
1562
 
1566
- 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)[]
1567
1564
  ? (Omit<A, keyof U> & U)[]
1568
1565
  : keyof U extends never
1569
1566
  ? T
1570
1567
  : Omit<T, keyof U> & U;
1571
1568
 
1572
- 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>;
1573
1570
 
1574
- class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1571
+ export class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1575
1572
  _mongooseOptions: MongooseQueryOptions<DocType>;
1576
1573
 
1577
1574
  /**
@@ -1676,7 +1673,7 @@ declare module 'mongoose' {
1676
1673
 
1677
1674
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1678
1675
  elemMatch(val: Function | any): this;
1679
- elemMatch(path: string, val: Function | any): this;
1676
+ elemMatch<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$elemMatch']): this;
1680
1677
 
1681
1678
  /**
1682
1679
  * Gets/sets the error flag on this query. If this flag is not null or
@@ -1693,7 +1690,7 @@ declare module 'mongoose' {
1693
1690
 
1694
1691
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1695
1692
  exists(val: boolean): this;
1696
- exists(path: string, val: boolean): this;
1693
+ exists<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$exists']): this;
1697
1694
 
1698
1695
  /**
1699
1696
  * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
@@ -1808,18 +1805,18 @@ declare module 'mongoose' {
1808
1805
 
1809
1806
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1810
1807
  gt(val: number): this;
1811
- gt(path: string, val: number): this;
1808
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gt']): this;
1812
1809
 
1813
1810
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1814
1811
  gte(val: number): this;
1815
- gte(path: string, val: number): this;
1812
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gte']): this;
1816
1813
 
1817
1814
  /** Sets query hints. */
1818
1815
  hint(val: any): this;
1819
1816
 
1820
1817
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1821
1818
  in(val: Array<any>): this;
1822
- in(path: string, val: Array<any>): this;
1819
+ in<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$in']): this;
1823
1820
 
1824
1821
  /** Declares an intersects query for `geometry()`. */
1825
1822
  intersects(arg?: any): this;
@@ -1835,11 +1832,11 @@ declare module 'mongoose' {
1835
1832
 
1836
1833
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1837
1834
  lt(val: number): this;
1838
- lt(path: string, val: number): this;
1835
+ lt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lt']): this;
1839
1836
 
1840
1837
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1841
1838
  lte(val: number): this;
1842
- lte(path: string, val: number): this;
1839
+ lte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lte']): this;
1843
1840
 
1844
1841
  /**
1845
1842
  * Runs a function `fn` and treats the return value of `fn` as the new value
@@ -1866,7 +1863,7 @@ declare module 'mongoose' {
1866
1863
 
1867
1864
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
1868
1865
  mod(val: Array<number>): this;
1869
- mod(path: string, val: Array<number>): this;
1866
+ mod<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$mod']): this;
1870
1867
 
1871
1868
  /** The model this query was created from */
1872
1869
  model: typeof Model;
@@ -1879,15 +1876,15 @@ declare module 'mongoose' {
1879
1876
 
1880
1877
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1881
1878
  ne(val: any): this;
1882
- ne(path: string, val: any): this;
1879
+ ne<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$ne']): this;
1883
1880
 
1884
1881
  /** Specifies a `$near` or `$nearSphere` condition */
1885
1882
  near(val: any): this;
1886
- near(path: string, val: any): this;
1883
+ near<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$near']): this;
1887
1884
 
1888
1885
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1889
1886
  nin(val: Array<any>): this;
1890
- nin(path: string, val: Array<any>): this;
1887
+ nin<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$nin']): this;
1891
1888
 
1892
1889
  /** Specifies arguments for an `$nor` condition. */
1893
1890
  nor(array: Array<FilterQuery<DocType>>): this;
@@ -1923,7 +1920,7 @@ declare module 'mongoose' {
1923
1920
 
1924
1921
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1925
1922
  regex(val: string | RegExp): this;
1926
- regex(path: string, val: string | RegExp): this;
1923
+ regex<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$regex']): this;
1927
1924
 
1928
1925
  /**
1929
1926
  * Declare and/or execute this query as a remove() operation. `remove()` is
@@ -1976,7 +1973,7 @@ declare module 'mongoose' {
1976
1973
 
1977
1974
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1978
1975
  size(val: number): this;
1979
- size(path: string, val: number): this;
1976
+ size<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$size']): this;
1980
1977
 
1981
1978
  /** Specifies the number of documents to skip. */
1982
1979
  skip(val: number): this;
@@ -2045,7 +2042,7 @@ declare module 'mongoose' {
2045
2042
  wtimeout(ms: number): this;
2046
2043
  }
2047
2044
 
2048
- type ProjectionElementType = number | string;
2045
+ export type ProjectionElementType = number | string;
2049
2046
  export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
2050
2047
 
2051
2048
  export type QuerySelector<T> = {
@@ -2115,10 +2112,10 @@ declare module 'mongoose' {
2115
2112
  [key: string]: any;
2116
2113
  };
2117
2114
 
2118
- type ApplyBasicQueryCasting<T> = T | T[] | any;
2119
- 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>>;
2120
2117
 
2121
- type _FilterQuery<T> = {
2118
+ export type _FilterQuery<T> = {
2122
2119
  [P in keyof T]?: Condition<T[P]>;
2123
2120
  } &
2124
2121
  RootQuerySelector<T>;
@@ -2132,20 +2129,7 @@ declare module 'mongoose' {
2132
2129
  */
2133
2130
  export type FilterQuery<T> = _FilterQuery<T>;
2134
2131
 
2135
- type AddToSetOperators<Type> = {
2136
- $each: Type;
2137
- };
2138
-
2139
- type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2140
-
2141
- type ArrayOperator<Type> = {
2142
- $each: Type;
2143
- $slice?: number;
2144
- $position?: number;
2145
- $sort?: SortValues | Record<string, SortValues>;
2146
- };
2147
-
2148
- type NumericTypes = number | Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;
2132
+ export type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2149
2133
 
2150
2134
  type _UpdateQuery<TSchema> = {
2151
2135
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
@@ -2172,18 +2156,18 @@ declare module 'mongoose' {
2172
2156
  };
2173
2157
  };
2174
2158
 
2175
- type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2176
- type UpdateAggregationStage = { $addFields: any } |
2159
+ export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2160
+ export type UpdateAggregationStage = { $addFields: any } |
2177
2161
  { $set: any } |
2178
2162
  { $project: any } |
2179
2163
  { $unset: any } |
2180
2164
  { $replaceRoot: any } |
2181
2165
  { $replaceWith: any };
2182
2166
 
2183
- type __UpdateDefProperty<T> =
2167
+ export type __UpdateDefProperty<T> =
2184
2168
  [Extract<T, mongodb.ObjectId>] extends [never] ? T :
2185
2169
  T | string;
2186
- type _UpdateQueryDef<T> = {
2170
+ export type _UpdateQueryDef<T> = {
2187
2171
  [K in keyof T]?: __UpdateDefProperty<T[K]>;
2188
2172
  };
2189
2173
 
@@ -2211,17 +2195,27 @@ declare module 'mongoose' {
2211
2195
  ? T[K] : FlattenMaps<T[K]>;
2212
2196
  };
2213
2197
 
2214
- type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2215
- type TreatAsPrimitives = actualPrimitives |
2216
- 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;
2217
2200
 
2218
- type LeanType<T> =
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'>;
2203
+
2204
+ export type LeanType<T> =
2219
2205
  0 extends (1 & T) ? T : // any
2220
2206
  T extends TreatAsPrimitives ? T : // primitives
2221
- T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> : // subdocs
2207
+ T extends Types.Subdocument ? LeanSubdocument<T> : // subdocs
2222
2208
  LeanDocument<T>; // Documents and everything else
2223
2209
 
2224
- 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]>[];
2225
2219
 
2226
2220
  export type _LeanDocument<T> = {
2227
2221
  [K in keyof T]: LeanDocumentElement<T[K]>;
@@ -2230,19 +2224,47 @@ declare module 'mongoose' {
2230
2224
  // Keep this a separate type, to ensure that T is a naked type.
2231
2225
  // This way, the conditional type is distributive over union types.
2232
2226
  // This is required for PopulatedDoc.
2233
- type LeanDocumentElement<T> =
2234
- T extends unknown[] ? LeanArray<T> : // Array
2235
- T extends Document ? LeanDocument<T> : // Subdocument
2236
- 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;
2237
2232
 
2238
2233
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
2239
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
+
2240
2261
  /**
2241
2262
  * Documents returned from queries with the lean option enabled.
2242
2263
  * Plain old JavaScript object documents (POJO).
2243
2264
  * @see https://mongoosejs.com/docs/tutorials/lean.html
2244
2265
  */
2245
- 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'>;
2246
2268
 
2247
2269
  export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
2248
2270
  T extends unknown[] ? LeanDocument<T[number]>[] :
@@ -2254,7 +2276,7 @@ declare module 'mongoose' {
2254
2276
  T extends Document ? RawDocType :
2255
2277
  T;
2256
2278
 
2257
- class SchemaType {
2279
+ export class SchemaType<T = any> {
2258
2280
  /** SchemaType constructor */
2259
2281
  constructor(path: string, options?: AnyObject, instance?: string);
2260
2282
 
@@ -2270,7 +2292,7 @@ declare module 'mongoose' {
2270
2292
  static get(getter: (value: any) => any): void;
2271
2293
 
2272
2294
  /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
2273
- OptionsConstructor: typeof SchemaTypeOptions;
2295
+ OptionsConstructor: SchemaTypeOptions<T>;
2274
2296
 
2275
2297
  /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
2276
2298
  cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
@@ -2347,14 +2369,14 @@ declare module 'mongoose' {
2347
2369
  continueOnError?: boolean
2348
2370
  }
2349
2371
  export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
2350
- type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2351
- 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;
2352
2374
 
2353
- type CallbackWithoutResult = (error: CallbackError) => void;
2354
- type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2375
+ export type CallbackWithoutResult = (error: CallbackError) => void;
2376
+ export type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2355
2377
 
2356
2378
  /* for ts-mongoose */
2357
- class mquery {}
2358
- }
2379
+ export class mquery { }
2359
2380
 
2360
- export default mongoose;
2381
+ export default mongoose;
2382
+ }