mongoose 6.3.1 → 6.3.4

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,23 +221,26 @@ 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
 
240
+ interface MongooseBulkWriteOptions {
241
+ skipValidation?: boolean;
242
+ }
243
+
243
244
  interface IndexesDiff {
244
245
  /** Indexes that would be created in mongodb. */
245
246
  toCreate: Array<any>
@@ -247,7 +248,7 @@ declare module 'mongoose' {
247
248
  toDrop: Array<any>
248
249
  }
249
250
 
250
- interface ModifyResult<T> {
251
+ export interface ModifyResult<T> {
251
252
  value: Require_id<T> | null;
252
253
  /** see https://www.mongodb.com/docs/manual/reference/command/findAndModify/#lasterrorobject */
253
254
  lastErrorObject?: {
@@ -258,14 +259,14 @@ declare module 'mongoose' {
258
259
  }
259
260
 
260
261
  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>;
262
+ export interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}> extends NodeJS.EventEmitter, AcceptsDiscriminator {
263
+ new <DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
263
264
 
264
265
  aggregate<R = any>(pipeline?: PipelineStage[], options?: mongodb.AggregateOptions, callback?: Callback<R[]>): Aggregate<Array<R>>;
265
266
  aggregate<R = any>(pipeline: PipelineStage[], cb: Function): Aggregate<Array<R>>;
266
267
 
267
268
  /** Base Mongoose instance the model uses. */
268
- base: typeof mongoose;
269
+ base: Mongoose;
269
270
 
270
271
  /**
271
272
  * If this is a discriminator model, `baseModelName` is the name of
@@ -280,8 +281,8 @@ declare module 'mongoose' {
280
281
  * if you use `create()`) because with `bulkWrite()` there is only one network
281
282
  * round trip to the MongoDB server.
282
283
  */
283
- bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions): Promise<mongodb.BulkWriteResult>;
284
- bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions, cb?: Callback<mongodb.BulkWriteResult>): void;
284
+ bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions): Promise<mongodb.BulkWriteResult>;
285
+ bulkWrite(writes: Array<any>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions, cb?: Callback<mongodb.BulkWriteResult>): void;
285
286
 
286
287
  /**
287
288
  * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than
@@ -464,7 +465,7 @@ declare module 'mongoose' {
464
465
  /** Casts and validates the given object against this model's schema, passing the given `context` to custom validators. */
465
466
  validate(callback?: CallbackWithoutResult): Promise<void>;
466
467
  validate(optional: any, callback?: CallbackWithoutResult): Promise<void>;
467
- validate(optional: any, pathsToValidate: string[], callback?: CallbackWithoutResult): Promise<void>;
468
+ validate(optional: any, pathsToValidate: pathsToValidate, callback?: CallbackWithoutResult): Promise<void>;
468
469
 
469
470
  /** Watches the underlying collection for changes using [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). */
470
471
  watch<ResultType extends mongodb.Document = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
@@ -607,9 +608,9 @@ declare module 'mongoose' {
607
608
  where<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
608
609
  }
609
610
 
610
- type UpdateWriteOpResult = mongodb.UpdateResult;
611
+ export type UpdateWriteOpResult = mongodb.UpdateResult;
611
612
 
612
- interface QueryOptions<DocType = unknown> {
613
+ export interface QueryOptions<DocType = unknown> {
613
614
  arrayFilters?: { [key: string]: any }[];
614
615
  batchSize?: number;
615
616
  collation?: mongodb.CollationOptions;
@@ -684,9 +685,9 @@ declare module 'mongoose' {
684
685
  [other: string]: any;
685
686
  }
686
687
 
687
- type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
688
+ export type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
688
689
 
689
- interface SaveOptions {
690
+ export interface SaveOptions {
690
691
  checkKeys?: boolean;
691
692
  j?: boolean;
692
693
  safe?: boolean | WriteConcern;
@@ -698,17 +699,17 @@ declare module 'mongoose' {
698
699
  wtimeout?: number;
699
700
  }
700
701
 
701
- interface WriteConcern {
702
+ export interface WriteConcern {
702
703
  j?: boolean;
703
704
  w?: number | 'majority' | TagSet;
704
705
  wtimeout?: number;
705
706
  }
706
707
 
707
- interface TagSet {
708
+ export interface TagSet {
708
709
  [k: string]: string;
709
710
  }
710
711
 
711
- interface InsertManyOptions {
712
+ export interface InsertManyOptions {
712
713
  limit?: number;
713
714
  rawResult?: boolean;
714
715
  ordered?: boolean;
@@ -717,15 +718,15 @@ declare module 'mongoose' {
717
718
  populate?: string | string[] | PopulateOptions | PopulateOptions[];
718
719
  }
719
720
 
720
- type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
721
- type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
721
+ export type InferIdType<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
722
+ export type InsertManyResult<T> = mongodb.InsertManyResult<T> & {
722
723
  insertedIds: {
723
724
  [key: number]: InferIdType<T>;
724
725
  };
725
726
  mongoose?: { validationErrors?: Array<Error.CastError | Error.ValidatorError> };
726
727
  };
727
728
 
728
- interface MapReduceOptions<T, Key, Val> {
729
+ export interface MapReduceOptions<T, Key, Val> {
729
730
  map: Function | string;
730
731
  reduce: (key: Key, vals: T[]) => Val;
731
732
  /** query filter object. */
@@ -767,7 +768,7 @@ declare module 'mongoose' {
767
768
  };
768
769
  }
769
770
 
770
- interface GeoSearchOptions {
771
+ export interface GeoSearchOptions {
771
772
  /** x,y point to search for */
772
773
  near: number[];
773
774
  /** the maximum distance from the point near that a result can be */
@@ -778,7 +779,7 @@ declare module 'mongoose' {
778
779
  lean?: boolean;
779
780
  }
780
781
 
781
- interface PopulateOptions {
782
+ export interface PopulateOptions {
782
783
  /** space delimited path(s) to populate */
783
784
  path: string;
784
785
  /** fields to select */
@@ -804,7 +805,7 @@ declare module 'mongoose' {
804
805
  transform?: (doc: any, id: any) => any;
805
806
  }
806
807
 
807
- interface ToObjectOptions {
808
+ export interface ToObjectOptions {
808
809
  /** apply all getters (path and virtual getters) */
809
810
  getters?: boolean;
810
811
  /** apply virtual getters (can override getters option) */
@@ -825,21 +826,21 @@ declare module 'mongoose' {
825
826
  useProjection?: boolean;
826
827
  }
827
828
 
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';
829
+ export type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
830
+ export type MongooseQueryMiddleware = 'count' | 'deleteMany' | 'deleteOne' | 'distinct' | 'find' | 'findOne' | 'findOneAndDelete' | 'findOneAndRemove' | 'findOneAndUpdate' | 'remove' | 'update' | 'updateOne' | 'updateMany';
830
831
 
831
- type SchemaPreOptions = { document?: boolean, query?: boolean };
832
- type SchemaPostOptions = { document?: boolean, query?: boolean };
832
+ export type SchemaPreOptions = { document?: boolean, query?: boolean };
833
+ export type SchemaPostOptions = { document?: boolean, query?: boolean };
833
834
 
834
- type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
835
- type IndexDefinition = Record<string, IndexDirection>;
835
+ export type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
836
+ export type IndexDefinition = Record<string, IndexDirection>;
836
837
 
837
838
  export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
838
839
  export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
839
840
  export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
840
841
  export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
841
842
 
842
- class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}> extends events.EventEmitter {
843
+ export class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}> extends events.EventEmitter {
843
844
  /**
844
845
  * Create a new schema
845
846
  */
@@ -986,13 +987,13 @@ declare module 'mongoose' {
986
987
  virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
987
988
  }
988
989
 
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;
990
+ export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
991
+ export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
992
+ export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
993
+ export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
994
+ export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
994
995
 
995
- type SchemaDefinitionWithBuiltInClass<T> = T extends number
996
+ export type SchemaDefinitionWithBuiltInClass<T> = T extends number
996
997
  ? NumberSchemaDefinition
997
998
  : T extends string
998
999
  ? StringSchemaDefinition
@@ -1002,7 +1003,7 @@ declare module 'mongoose' {
1002
1003
  ? DateSchemaDefinition
1003
1004
  : (Function | string);
1004
1005
 
1005
- type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1006
+ export type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1006
1007
  SchemaTypeOptions<T extends undefined ? any : T> |
1007
1008
  typeof SchemaType |
1008
1009
  Schema<any, any, any> |
@@ -1014,24 +1015,24 @@ declare module 'mongoose' {
1014
1015
  typeof Schema.Types.Mixed |
1015
1016
  MixedSchemaTypeOptions;
1016
1017
 
1017
- type SchemaDefinition<T = undefined> = T extends undefined
1018
+ export type SchemaDefinition<T = undefined> = T extends undefined
1018
1019
  ? { [path: string]: SchemaDefinitionProperty; }
1019
1020
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
1020
1021
 
1021
- type Unpacked<T> = T extends (infer U)[] ?
1022
+ export type Unpacked<T> = T extends (infer U)[] ?
1022
1023
  U :
1023
1024
  T extends ReadonlyArray<infer U> ? U : T;
1024
1025
 
1025
- type AnyArray<T> = T[] | ReadonlyArray<T>;
1026
- type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1026
+ export type AnyArray<T> = T[] | ReadonlyArray<T>;
1027
+ export type SchemaValidator<T> = RegExp | [RegExp, string] | Function | [Function, string] | ValidateOpts<T> | ValidateOpts<T>[];
1027
1028
 
1028
- type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
1029
+ export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
1029
1030
 
1030
- class MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1031
+ export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1031
1032
  type: typeof Schema.Types.Mixed;
1032
1033
  }
1033
1034
 
1034
- export class SchemaTypeOptions<T> {
1035
+ export interface SchemaTypeOptions<T> {
1035
1036
  type?:
1036
1037
  T extends string ? StringSchemaDefinition :
1037
1038
  T extends number ? NumberSchemaDefinition :
@@ -1120,7 +1121,7 @@ declare module 'mongoose' {
1120
1121
  transform?: (this: any, val: T) => any;
1121
1122
 
1122
1123
  /** 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;
1124
+ get?: (value: any, doc?: this) => T;
1124
1125
 
1125
1126
  /** 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
1127
  set?: (value: any, priorVal?: T, doc?: this) => any;
@@ -1178,22 +1179,22 @@ declare module 'mongoose' {
1178
1179
  | string
1179
1180
  | Buffer
1180
1181
  | 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;
1182
+ | Types.ObjectId
1183
+ | Types.Buffer
1184
+ | typeof Schema.Types.Number
1185
+ | typeof Schema.Types.String
1186
+ | typeof Schema.Types.Buffer
1187
+ | typeof Schema.Types.ObjectId;
1187
1188
 
1188
1189
  /**
1189
1190
  * Reference another Model
1190
1191
  */
1191
1192
  export type PopulatedDoc<
1192
1193
  PopulatedType,
1193
- RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined
1194
+ RawId extends RefType = (PopulatedType extends { _id?: RefType; } ? NonNullable<PopulatedType['_id']> : Types.ObjectId) | undefined
1194
1195
  > = PopulatedType | RawId;
1195
1196
 
1196
- interface IndexOptions extends mongodb.CreateIndexesOptions {
1197
+ export interface IndexOptions extends mongodb.CreateIndexesOptions {
1197
1198
  /**
1198
1199
  * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
1199
1200
  *
@@ -1218,37 +1219,37 @@ declare module 'mongoose' {
1218
1219
  weights?: AnyObject;
1219
1220
  }
1220
1221
 
1221
- interface ValidatorProps {
1222
+ export interface ValidatorProps {
1222
1223
  path: string;
1223
1224
  value: any;
1224
1225
  }
1225
1226
 
1226
- interface ValidatorMessageFn {
1227
+ export interface ValidatorMessageFn {
1227
1228
  (props: ValidatorProps): string;
1228
1229
  }
1229
1230
 
1230
- interface ValidateFn<T> {
1231
+ export interface ValidateFn<T> {
1231
1232
  (value: T): boolean;
1232
1233
  }
1233
1234
 
1234
- interface LegacyAsyncValidateFn<T> {
1235
+ export interface LegacyAsyncValidateFn<T> {
1235
1236
  (value: T, done: (result: boolean) => void): void;
1236
1237
  }
1237
1238
 
1238
- interface AsyncValidateFn<T> {
1239
+ export interface AsyncValidateFn<T> {
1239
1240
  (value: any): Promise<boolean>;
1240
1241
  }
1241
1242
 
1242
- interface ValidateOpts<T> {
1243
+ export interface ValidateOpts<T> {
1243
1244
  msg?: string;
1244
1245
  message?: string | ValidatorMessageFn;
1245
1246
  type?: string;
1246
1247
  validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
1247
1248
  }
1248
1249
 
1249
- type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1250
+ export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1250
1251
 
1251
- interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1252
+ export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1252
1253
  /** If `ref` is not nullish, this becomes a populated virtual. */
1253
1254
  ref?: string | Function;
1254
1255
 
@@ -1298,7 +1299,7 @@ declare module 'mongoose' {
1298
1299
  [extra: string]: any;
1299
1300
  }
1300
1301
 
1301
- class VirtualType<HydratedDocType> {
1302
+ export class VirtualType<HydratedDocType> {
1302
1303
  /** Applies getters to `value`. */
1303
1304
  applyGetters(value: any, doc: Document): any;
1304
1305
 
@@ -1312,7 +1313,7 @@ declare module 'mongoose' {
1312
1313
  set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
1313
1314
  }
1314
1315
 
1315
- namespace Schema {
1316
+ export namespace Schema {
1316
1317
  namespace Types {
1317
1318
  class Array extends SchemaType implements AcceptsDiscriminator {
1318
1319
  /** This schema type's name, to defend against minifiers that mangle function names. */
@@ -1461,7 +1462,7 @@ declare module 'mongoose' {
1461
1462
  }
1462
1463
  }
1463
1464
 
1464
- namespace Types {
1465
+ export namespace Types {
1465
1466
  class Array<T> extends global.Array<T> {
1466
1467
  /** Pops the array atomically at most one time per document `save()`. */
1467
1468
  $pop(): T;
@@ -1559,19 +1560,19 @@ declare module 'mongoose' {
1559
1560
  }
1560
1561
  }
1561
1562
 
1562
- type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1563
+ export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1563
1564
 
1564
- type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1565
+ export type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
1565
1566
 
1566
- type UnpackedIntersection<T, U> = T extends null ? null : T extends (infer A)[]
1567
+ export type UnpackedIntersection<T, U> = T extends null ? null : T extends (infer A)[]
1567
1568
  ? (Omit<A, keyof U> & U)[]
1568
1569
  : keyof U extends never
1569
1570
  ? T
1570
1571
  : Omit<T, keyof U> & U;
1571
1572
 
1572
- type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
1573
+ export type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
1573
1574
 
1574
- class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1575
+ export class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1575
1576
  _mongooseOptions: MongooseQueryOptions<DocType>;
1576
1577
 
1577
1578
  /**
@@ -1676,7 +1677,7 @@ declare module 'mongoose' {
1676
1677
 
1677
1678
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1678
1679
  elemMatch(val: Function | any): this;
1679
- elemMatch(path: string, val: Function | any): this;
1680
+ elemMatch<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$elemMatch']): this;
1680
1681
 
1681
1682
  /**
1682
1683
  * Gets/sets the error flag on this query. If this flag is not null or
@@ -1693,7 +1694,7 @@ declare module 'mongoose' {
1693
1694
 
1694
1695
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1695
1696
  exists(val: boolean): this;
1696
- exists(path: string, val: boolean): this;
1697
+ exists<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$exists']): this;
1697
1698
 
1698
1699
  /**
1699
1700
  * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
@@ -1808,18 +1809,18 @@ declare module 'mongoose' {
1808
1809
 
1809
1810
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1810
1811
  gt(val: number): this;
1811
- gt(path: string, val: number): this;
1812
+ gt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gt']): this;
1812
1813
 
1813
1814
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1814
1815
  gte(val: number): this;
1815
- gte(path: string, val: number): this;
1816
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gte']): this;
1816
1817
 
1817
1818
  /** Sets query hints. */
1818
1819
  hint(val: any): this;
1819
1820
 
1820
1821
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1821
1822
  in(val: Array<any>): this;
1822
- in(path: string, val: Array<any>): this;
1823
+ in<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$in']): this;
1823
1824
 
1824
1825
  /** Declares an intersects query for `geometry()`. */
1825
1826
  intersects(arg?: any): this;
@@ -1835,11 +1836,11 @@ declare module 'mongoose' {
1835
1836
 
1836
1837
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1837
1838
  lt(val: number): this;
1838
- lt(path: string, val: number): this;
1839
+ lt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lt']): this;
1839
1840
 
1840
1841
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1841
1842
  lte(val: number): this;
1842
- lte(path: string, val: number): this;
1843
+ lte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lte']): this;
1843
1844
 
1844
1845
  /**
1845
1846
  * Runs a function `fn` and treats the return value of `fn` as the new value
@@ -1866,7 +1867,7 @@ declare module 'mongoose' {
1866
1867
 
1867
1868
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
1868
1869
  mod(val: Array<number>): this;
1869
- mod(path: string, val: Array<number>): this;
1870
+ mod<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$mod']): this;
1870
1871
 
1871
1872
  /** The model this query was created from */
1872
1873
  model: typeof Model;
@@ -1879,15 +1880,15 @@ declare module 'mongoose' {
1879
1880
 
1880
1881
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1881
1882
  ne(val: any): this;
1882
- ne(path: string, val: any): this;
1883
+ ne<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$ne']): this;
1883
1884
 
1884
1885
  /** Specifies a `$near` or `$nearSphere` condition */
1885
1886
  near(val: any): this;
1886
- near(path: string, val: any): this;
1887
+ near<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$near']): this;
1887
1888
 
1888
1889
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1889
1890
  nin(val: Array<any>): this;
1890
- nin(path: string, val: Array<any>): this;
1891
+ nin<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$nin']): this;
1891
1892
 
1892
1893
  /** Specifies arguments for an `$nor` condition. */
1893
1894
  nor(array: Array<FilterQuery<DocType>>): this;
@@ -1923,7 +1924,7 @@ declare module 'mongoose' {
1923
1924
 
1924
1925
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1925
1926
  regex(val: string | RegExp): this;
1926
- regex(path: string, val: string | RegExp): this;
1927
+ regex<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$regex']): this;
1927
1928
 
1928
1929
  /**
1929
1930
  * Declare and/or execute this query as a remove() operation. `remove()` is
@@ -1976,7 +1977,7 @@ declare module 'mongoose' {
1976
1977
 
1977
1978
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1978
1979
  size(val: number): this;
1979
- size(path: string, val: number): this;
1980
+ size<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$size']): this;
1980
1981
 
1981
1982
  /** Specifies the number of documents to skip. */
1982
1983
  skip(val: number): this;
@@ -2045,7 +2046,7 @@ declare module 'mongoose' {
2045
2046
  wtimeout(ms: number): this;
2046
2047
  }
2047
2048
 
2048
- type ProjectionElementType = number | string;
2049
+ export type ProjectionElementType = number | string;
2049
2050
  export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
2050
2051
 
2051
2052
  export type QuerySelector<T> = {
@@ -2115,10 +2116,10 @@ declare module 'mongoose' {
2115
2116
  [key: string]: any;
2116
2117
  };
2117
2118
 
2118
- type ApplyBasicQueryCasting<T> = T | T[] | any;
2119
- type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
2119
+ export type ApplyBasicQueryCasting<T> = T | T[] | any;
2120
+ export type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
2120
2121
 
2121
- type _FilterQuery<T> = {
2122
+ export type _FilterQuery<T> = {
2122
2123
  [P in keyof T]?: Condition<T[P]>;
2123
2124
  } &
2124
2125
  RootQuerySelector<T>;
@@ -2132,20 +2133,7 @@ declare module 'mongoose' {
2132
2133
  */
2133
2134
  export type FilterQuery<T> = _FilterQuery<T>;
2134
2135
 
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;
2136
+ export type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2149
2137
 
2150
2138
  type _UpdateQuery<TSchema> = {
2151
2139
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
@@ -2172,18 +2160,18 @@ declare module 'mongoose' {
2172
2160
  };
2173
2161
  };
2174
2162
 
2175
- type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2176
- type UpdateAggregationStage = { $addFields: any } |
2163
+ export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2164
+ export type UpdateAggregationStage = { $addFields: any } |
2177
2165
  { $set: any } |
2178
2166
  { $project: any } |
2179
2167
  { $unset: any } |
2180
2168
  { $replaceRoot: any } |
2181
2169
  { $replaceWith: any };
2182
2170
 
2183
- type __UpdateDefProperty<T> =
2171
+ export type __UpdateDefProperty<T> =
2184
2172
  [Extract<T, mongodb.ObjectId>] extends [never] ? T :
2185
2173
  T | string;
2186
- type _UpdateQueryDef<T> = {
2174
+ export type _UpdateQueryDef<T> = {
2187
2175
  [K in keyof T]?: __UpdateDefProperty<T[K]>;
2188
2176
  };
2189
2177
 
@@ -2211,17 +2199,27 @@ declare module 'mongoose' {
2211
2199
  ? T[K] : FlattenMaps<T[K]>;
2212
2200
  };
2213
2201
 
2214
- type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2215
- type TreatAsPrimitives = actualPrimitives |
2216
- NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
2202
+ export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2203
+ export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
2204
+
2205
+ // This will -- when possible -- extract the original type of the subdocument in question
2206
+ type LeanSubdocument<T> = T extends (Types.Subdocument<Require_id<T>['_id']> & infer U) ? LeanDocument<U> : Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'>;
2217
2207
 
2218
- type LeanType<T> =
2208
+ export type LeanType<T> =
2219
2209
  0 extends (1 & T) ? T : // any
2220
2210
  T extends TreatAsPrimitives ? T : // primitives
2221
- T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> : // subdocs
2211
+ T extends Types.Subdocument ? LeanSubdocument<T> : // subdocs
2222
2212
  LeanDocument<T>; // Documents and everything else
2223
2213
 
2224
- type LeanArray<T extends unknown[]> = T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
2214
+ // Used only when collapsing lean arrays for ts performance reasons:
2215
+ type LeanTypeOrArray<T> = T extends unknown[] ? LeanArray<T> : LeanType<T>;
2216
+
2217
+ export type LeanArray<T extends unknown[]> =
2218
+ // By checking if it extends Types.Array we can get the original base type before collapsing down,
2219
+ // rather than trying to manually remove the old types. This matches both Array and DocumentArray
2220
+ T extends Types.Array<infer U> ? LeanTypeOrArray<U>[] :
2221
+ // If it isn't a custom mongoose type we fall back to "do our best"
2222
+ T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
2225
2223
 
2226
2224
  export type _LeanDocument<T> = {
2227
2225
  [K in keyof T]: LeanDocumentElement<T[K]>;
@@ -2230,19 +2228,47 @@ declare module 'mongoose' {
2230
2228
  // Keep this a separate type, to ensure that T is a naked type.
2231
2229
  // This way, the conditional type is distributive over union types.
2232
2230
  // 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;
2231
+ export type LeanDocumentElement<T> =
2232
+ 0 extends (1 & T) ? T :// any
2233
+ T extends unknown[] ? LeanArray<T> : // Array
2234
+ T extends Document ? LeanDocument<T> : // Subdocument
2235
+ T;
2237
2236
 
2238
2237
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
2239
2238
 
2239
+ // Helpers to simplify checks
2240
+ type IfAny<IFTYPE, THENTYPE> = 0 extends (1 & IFTYPE) ? THENTYPE : IFTYPE;
2241
+ type IfUnknown<IFTYPE, THENTYPE> = unknown extends IFTYPE ? THENTYPE : IFTYPE;
2242
+
2243
+ // tests for these two types are located in test/types/lean.test.ts
2244
+ export type DocTypeFromUnion<T> = T extends (Document<infer T1, infer T2, infer T3> & infer U) ?
2245
+ [U] extends [Document<T1, T2, T3> & infer U] ? IfUnknown<IfAny<U, false>, false> : false : false;
2246
+
2247
+ export type DocTypeFromGeneric<T> = T extends Document<infer IdType, infer TQueryHelpers, infer DocType> ?
2248
+ IfUnknown<IfAny<DocType, false>, false> : false;
2249
+
2250
+ /**
2251
+ * Helper to choose the best option between two type helpers
2252
+ */
2253
+ export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
2254
+
2255
+ /**
2256
+ * There may be a better way to do this, but the goal is to return the DocType if it can be infered
2257
+ * and if not to return a type which is easily identified as "not valid" so we fall back to
2258
+ * "strip out known things added by extending Document"
2259
+ * There are three basic ways to mix in Document -- "Document & T", "Document<ObjId, mixins, T>",
2260
+ * and "T extends Document". In the last case there is no type without Document mixins, so we can only
2261
+ * strip things out. In the other two cases we can infer the type, so we should
2262
+ */
2263
+ export type BaseDocumentType<T> = _pickObject<DocTypeFromUnion<T>, DocTypeFromGeneric<T>, false>;
2264
+
2240
2265
  /**
2241
2266
  * Documents returned from queries with the lean option enabled.
2242
2267
  * Plain old JavaScript object documents (POJO).
2243
2268
  * @see https://mongoosejs.com/docs/tutorials/lean.html
2244
2269
  */
2245
- export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
2270
+ export type LeanDocument<T> = BaseDocumentType<T> extends Document ? _LeanDocument<BaseDocumentType<T>> :
2271
+ Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
2246
2272
 
2247
2273
  export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
2248
2274
  T extends unknown[] ? LeanDocument<T[number]>[] :
@@ -2250,11 +2276,11 @@ declare module 'mongoose' {
2250
2276
  T;
2251
2277
 
2252
2278
  export type LeanDocumentOrArrayWithRawType<T, RawDocType> = 0 extends (1 & T) ? T :
2253
- T extends unknown[] ? RawDocType[] :
2254
- T extends Document ? RawDocType :
2279
+ T extends unknown[] ? LeanDocument<RawDocType>[] :
2280
+ T extends Document ? LeanDocument<RawDocType> :
2255
2281
  T;
2256
2282
 
2257
- class SchemaType {
2283
+ export class SchemaType<T = any> {
2258
2284
  /** SchemaType constructor */
2259
2285
  constructor(path: string, options?: AnyObject, instance?: string);
2260
2286
 
@@ -2270,7 +2296,7 @@ declare module 'mongoose' {
2270
2296
  static get(getter: (value: any) => any): void;
2271
2297
 
2272
2298
  /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
2273
- OptionsConstructor: typeof SchemaTypeOptions;
2299
+ OptionsConstructor: SchemaTypeOptions<T>;
2274
2300
 
2275
2301
  /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
2276
2302
  cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
@@ -2347,14 +2373,14 @@ declare module 'mongoose' {
2347
2373
  continueOnError?: boolean
2348
2374
  }
2349
2375
  export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
2350
- type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2351
- type Callback<T = any> = (error: CallbackError, result: T) => void;
2376
+ export type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2377
+ export type Callback<T = any> = (error: CallbackError, result: T) => void;
2352
2378
 
2353
- type CallbackWithoutResult = (error: CallbackError) => void;
2354
- type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2379
+ export type CallbackWithoutResult = (error: CallbackError) => void;
2380
+ export type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2355
2381
 
2356
2382
  /* for ts-mongoose */
2357
- class mquery {}
2358
- }
2383
+ export class mquery { }
2359
2384
 
2360
- export default mongoose;
2385
+ export default mongoose;
2386
+ }