mongoose 6.3.0 → 6.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/.eslintrc.json +157 -157
  2. package/README.md +2 -2
  3. package/dist/browser.umd.js +1 -1
  4. package/lib/collection.js +0 -7
  5. package/lib/connection.js +2 -1
  6. package/lib/document.js +65 -68
  7. package/lib/error/cast.js +8 -2
  8. package/lib/helpers/common.js +0 -8
  9. package/lib/helpers/immediate.js +3 -1
  10. package/lib/helpers/isAsyncFunction.js +19 -7
  11. package/lib/helpers/model/castBulkWrite.js +12 -0
  12. package/lib/helpers/populate/getModelsMapForPopulate.js +13 -10
  13. package/lib/helpers/query/cast$expr.js +4 -1
  14. package/lib/helpers/schematype/handleImmutable.js +4 -1
  15. package/lib/helpers/timestamps/setupTimestamps.js +2 -2
  16. package/lib/index.js +1 -1
  17. package/lib/internal.js +0 -1
  18. package/lib/model.js +42 -28
  19. package/lib/query.js +7 -3
  20. package/lib/queryhelpers.js +11 -1
  21. package/lib/schema/SubdocumentPath.js +3 -15
  22. package/lib/schema/documentarray.js +7 -7
  23. package/lib/schema/number.js +1 -5
  24. package/lib/schema/objectid.js +2 -4
  25. package/lib/schema/string.js +3 -6
  26. package/lib/schema.js +1 -1
  27. package/lib/schematype.js +2 -2
  28. package/lib/types/DocumentArray/methods/index.js +9 -1
  29. package/lib/types/array/methods/index.js +8 -9
  30. package/lib/utils.js +4 -0
  31. package/package.json +39 -19
  32. package/tsconfig.json +2 -2
  33. package/types/aggregate.d.ts +1 -2
  34. package/types/connection.d.ts +4 -5
  35. package/types/cursor.d.ts +3 -2
  36. package/types/document.d.ts +18 -15
  37. package/types/error.d.ts +124 -124
  38. package/types/index.d.ts +182 -154
  39. package/types/mongooseoptions.d.ts +1 -2
  40. package/types/schemaoptions.d.ts +1 -2
  41. package/CHANGELOG.md +0 -7249
  42. package/History.md +0 -1
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,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
@@ -317,8 +318,8 @@ declare module 'mongoose' {
317
318
  * mongoose will not create the collection for the model until any documents are
318
319
  * created. Use this method to create the collection explicitly.
319
320
  */
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;
321
+ createCollection<T extends mongodb.Document>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
322
+ createCollection<T extends mongodb.Document>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
322
323
 
323
324
  /**
324
325
  * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex)
@@ -464,10 +465,10 @@ 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
- watch<ResultType = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
471
+ watch<ResultType extends mongodb.Document = any>(pipeline?: Array<Record<string, unknown>>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;
471
472
 
472
473
  /** Adds a `$where` clause to this query */
473
474
  $where(argument: string | Function): QueryWithHelpers<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
@@ -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 */
@@ -789,6 +790,8 @@ declare module 'mongoose' {
789
790
  model?: string | Model<any>;
790
791
  /** optional query options like sort, limit, etc */
791
792
  options?: any;
793
+ /** correct limit on populated array */
794
+ perDocumentLimit?: number;
792
795
  /** optional boolean, set to `false` to allow populating paths that aren't in the schema */
793
796
  strictPopulate?: boolean;
794
797
  /** deep populate */
@@ -802,7 +805,7 @@ declare module 'mongoose' {
802
805
  transform?: (doc: any, id: any) => any;
803
806
  }
804
807
 
805
- interface ToObjectOptions {
808
+ export interface ToObjectOptions {
806
809
  /** apply all getters (path and virtual getters) */
807
810
  getters?: boolean;
808
811
  /** apply virtual getters (can override getters option) */
@@ -823,21 +826,21 @@ declare module 'mongoose' {
823
826
  useProjection?: boolean;
824
827
  }
825
828
 
826
- type MongooseDocumentMiddleware = 'validate' | 'save' | 'remove' | 'updateOne' | 'deleteOne' | 'init';
827
- 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';
828
831
 
829
- type SchemaPreOptions = { document?: boolean, query?: boolean };
830
- type SchemaPostOptions = { document?: boolean, query?: boolean };
832
+ export type SchemaPreOptions = { document?: boolean, query?: boolean };
833
+ export type SchemaPostOptions = { document?: boolean, query?: boolean };
831
834
 
832
- type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
833
- type IndexDefinition = Record<string, IndexDirection>;
835
+ export type IndexDirection = 1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text';
836
+ export type IndexDefinition = Record<string, IndexDirection>;
834
837
 
835
838
  export type PreMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
836
839
  export type PreSaveMiddlewareFunction<ThisType = any> = (this: ThisType, next: CallbackWithoutResultAndOptionalError, opts: SaveOptions) => void | Promise<void>;
837
840
  export type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;
838
841
  export type ErrorHandlingMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, err: NativeError, res: ResType, next: CallbackWithoutResultAndOptionalError) => void;
839
842
 
840
- 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 {
841
844
  /**
842
845
  * Create a new schema
843
846
  */
@@ -975,22 +978,22 @@ declare module 'mongoose' {
975
978
  virtual<T = HydratedDocument<DocType, TInstanceMethods>>(
976
979
  name: string,
977
980
  options?: VirtualTypeOptions<T, DocType>
978
- ): VirtualType;
981
+ ): VirtualType<T>;
979
982
 
980
983
  /** Object of currently defined virtuals on this schema */
981
984
  virtuals: any;
982
985
 
983
986
  /** Returns the virtual type with the given `name`. */
984
- virtualpath(name: string): VirtualType | null;
987
+ virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
985
988
  }
986
989
 
987
- type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
988
- type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
989
- type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
990
- type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
991
- 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;
992
995
 
993
- type SchemaDefinitionWithBuiltInClass<T> = T extends number
996
+ export type SchemaDefinitionWithBuiltInClass<T> = T extends number
994
997
  ? NumberSchemaDefinition
995
998
  : T extends string
996
999
  ? StringSchemaDefinition
@@ -1000,7 +1003,7 @@ declare module 'mongoose' {
1000
1003
  ? DateSchemaDefinition
1001
1004
  : (Function | string);
1002
1005
 
1003
- type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1006
+ export type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
1004
1007
  SchemaTypeOptions<T extends undefined ? any : T> |
1005
1008
  typeof SchemaType |
1006
1009
  Schema<any, any, any> |
@@ -1012,24 +1015,24 @@ declare module 'mongoose' {
1012
1015
  typeof Schema.Types.Mixed |
1013
1016
  MixedSchemaTypeOptions;
1014
1017
 
1015
- type SchemaDefinition<T = undefined> = T extends undefined
1018
+ export type SchemaDefinition<T = undefined> = T extends undefined
1016
1019
  ? { [path: string]: SchemaDefinitionProperty; }
1017
1020
  : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
1018
1021
 
1019
- type Unpacked<T> = T extends (infer U)[] ?
1022
+ export type Unpacked<T> = T extends (infer U)[] ?
1020
1023
  U :
1021
1024
  T extends ReadonlyArray<infer U> ? U : T;
1022
1025
 
1023
- type AnyArray<T> = T[] | ReadonlyArray<T>;
1024
- 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>[];
1025
1028
 
1026
- 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;
1027
1030
 
1028
- class MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1031
+ export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
1029
1032
  type: typeof Schema.Types.Mixed;
1030
1033
  }
1031
1034
 
1032
- export class SchemaTypeOptions<T> {
1035
+ export interface SchemaTypeOptions<T> {
1033
1036
  type?:
1034
1037
  T extends string ? StringSchemaDefinition :
1035
1038
  T extends number ? NumberSchemaDefinition :
@@ -1118,7 +1121,7 @@ declare module 'mongoose' {
1118
1121
  transform?: (this: any, val: T) => any;
1119
1122
 
1120
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). */
1121
- get?: (value: T, doc?: this) => any;
1124
+ get?: (value: any, doc?: this) => T;
1122
1125
 
1123
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). */
1124
1127
  set?: (value: any, priorVal?: T, doc?: this) => any;
@@ -1176,22 +1179,22 @@ declare module 'mongoose' {
1176
1179
  | string
1177
1180
  | Buffer
1178
1181
  | undefined
1179
- | mongoose.Types.ObjectId
1180
- | mongoose.Types.Buffer
1181
- | typeof mongoose.Schema.Types.Number
1182
- | typeof mongoose.Schema.Types.String
1183
- | typeof mongoose.Schema.Types.Buffer
1184
- | 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;
1185
1188
 
1186
1189
  /**
1187
1190
  * Reference another Model
1188
1191
  */
1189
1192
  export type PopulatedDoc<
1190
1193
  PopulatedType,
1191
- 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
1192
1195
  > = PopulatedType | RawId;
1193
1196
 
1194
- interface IndexOptions extends mongodb.CreateIndexesOptions {
1197
+ export interface IndexOptions extends mongodb.CreateIndexesOptions {
1195
1198
  /**
1196
1199
  * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:
1197
1200
  *
@@ -1216,37 +1219,37 @@ declare module 'mongoose' {
1216
1219
  weights?: AnyObject;
1217
1220
  }
1218
1221
 
1219
- interface ValidatorProps {
1222
+ export interface ValidatorProps {
1220
1223
  path: string;
1221
1224
  value: any;
1222
1225
  }
1223
1226
 
1224
- interface ValidatorMessageFn {
1227
+ export interface ValidatorMessageFn {
1225
1228
  (props: ValidatorProps): string;
1226
1229
  }
1227
1230
 
1228
- interface ValidateFn<T> {
1231
+ export interface ValidateFn<T> {
1229
1232
  (value: T): boolean;
1230
1233
  }
1231
1234
 
1232
- interface LegacyAsyncValidateFn<T> {
1235
+ export interface LegacyAsyncValidateFn<T> {
1233
1236
  (value: T, done: (result: boolean) => void): void;
1234
1237
  }
1235
1238
 
1236
- interface AsyncValidateFn<T> {
1239
+ export interface AsyncValidateFn<T> {
1237
1240
  (value: any): Promise<boolean>;
1238
1241
  }
1239
1242
 
1240
- interface ValidateOpts<T> {
1243
+ export interface ValidateOpts<T> {
1241
1244
  msg?: string;
1242
1245
  message?: string | ValidatorMessageFn;
1243
1246
  type?: string;
1244
1247
  validator: ValidateFn<T> | LegacyAsyncValidateFn<T> | AsyncValidateFn<T>;
1245
1248
  }
1246
1249
 
1247
- type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1250
+ export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
1248
1251
 
1249
- interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1252
+ export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
1250
1253
  /** If `ref` is not nullish, this becomes a populated virtual. */
1251
1254
  ref?: string | Function;
1252
1255
 
@@ -1296,7 +1299,7 @@ declare module 'mongoose' {
1296
1299
  [extra: string]: any;
1297
1300
  }
1298
1301
 
1299
- class VirtualType {
1302
+ export class VirtualType<HydratedDocType> {
1300
1303
  /** Applies getters to `value`. */
1301
1304
  applyGetters(value: any, doc: Document): any;
1302
1305
 
@@ -1304,13 +1307,13 @@ declare module 'mongoose' {
1304
1307
  applySetters(value: any, doc: Document): any;
1305
1308
 
1306
1309
  /** Adds a custom getter to this virtual. */
1307
- get(fn: Function): this;
1310
+ get<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => any): this;
1308
1311
 
1309
1312
  /** Adds a custom setter to this virtual. */
1310
- set(fn: Function): this;
1313
+ set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
1311
1314
  }
1312
1315
 
1313
- namespace Schema {
1316
+ export namespace Schema {
1314
1317
  namespace Types {
1315
1318
  class Array extends SchemaType implements AcceptsDiscriminator {
1316
1319
  /** This schema type's name, to defend against minifiers that mangle function names. */
@@ -1459,7 +1462,7 @@ declare module 'mongoose' {
1459
1462
  }
1460
1463
  }
1461
1464
 
1462
- namespace Types {
1465
+ export namespace Types {
1463
1466
  class Array<T> extends global.Array<T> {
1464
1467
  /** Pops the array atomically at most one time per document `save()`. */
1465
1468
  $pop(): T;
@@ -1557,19 +1560,19 @@ declare module 'mongoose' {
1557
1560
  }
1558
1561
  }
1559
1562
 
1560
- type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1563
+ export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
1561
1564
 
1562
- 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;
1563
1566
 
1564
- 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)[]
1565
1568
  ? (Omit<A, keyof U> & U)[]
1566
1569
  : keyof U extends never
1567
1570
  ? T
1568
1571
  : Omit<T, keyof U> & U;
1569
1572
 
1570
- 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>;
1571
1574
 
1572
- class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1575
+ export class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> {
1573
1576
  _mongooseOptions: MongooseQueryOptions<DocType>;
1574
1577
 
1575
1578
  /**
@@ -1674,7 +1677,7 @@ declare module 'mongoose' {
1674
1677
 
1675
1678
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1676
1679
  elemMatch(val: Function | any): this;
1677
- elemMatch(path: string, val: Function | any): this;
1680
+ elemMatch<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$elemMatch']): this;
1678
1681
 
1679
1682
  /**
1680
1683
  * Gets/sets the error flag on this query. If this flag is not null or
@@ -1691,7 +1694,7 @@ declare module 'mongoose' {
1691
1694
 
1692
1695
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1693
1696
  exists(val: boolean): this;
1694
- exists(path: string, val: boolean): this;
1697
+ exists<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$exists']): this;
1695
1698
 
1696
1699
  /**
1697
1700
  * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/),
@@ -1806,18 +1809,18 @@ declare module 'mongoose' {
1806
1809
 
1807
1810
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1808
1811
  gt(val: number): this;
1809
- gt(path: string, val: number): this;
1812
+ gt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gt']): this;
1810
1813
 
1811
1814
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1812
1815
  gte(val: number): this;
1813
- gte(path: string, val: number): this;
1816
+ gte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$gte']): this;
1814
1817
 
1815
1818
  /** Sets query hints. */
1816
1819
  hint(val: any): this;
1817
1820
 
1818
1821
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1819
1822
  in(val: Array<any>): this;
1820
- in(path: string, val: Array<any>): this;
1823
+ in<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$in']): this;
1821
1824
 
1822
1825
  /** Declares an intersects query for `geometry()`. */
1823
1826
  intersects(arg?: any): this;
@@ -1833,11 +1836,11 @@ declare module 'mongoose' {
1833
1836
 
1834
1837
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1835
1838
  lt(val: number): this;
1836
- lt(path: string, val: number): this;
1839
+ lt<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lt']): this;
1837
1840
 
1838
1841
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1839
1842
  lte(val: number): this;
1840
- lte(path: string, val: number): this;
1843
+ lte<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$lte']): this;
1841
1844
 
1842
1845
  /**
1843
1846
  * Runs a function `fn` and treats the return value of `fn` as the new value
@@ -1864,7 +1867,7 @@ declare module 'mongoose' {
1864
1867
 
1865
1868
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
1866
1869
  mod(val: Array<number>): this;
1867
- mod(path: string, val: Array<number>): this;
1870
+ mod<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$mod']): this;
1868
1871
 
1869
1872
  /** The model this query was created from */
1870
1873
  model: typeof Model;
@@ -1877,15 +1880,15 @@ declare module 'mongoose' {
1877
1880
 
1878
1881
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1879
1882
  ne(val: any): this;
1880
- ne(path: string, val: any): this;
1883
+ ne<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$ne']): this;
1881
1884
 
1882
1885
  /** Specifies a `$near` or `$nearSphere` condition */
1883
1886
  near(val: any): this;
1884
- near(path: string, val: any): this;
1887
+ near<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$near']): this;
1885
1888
 
1886
1889
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1887
1890
  nin(val: Array<any>): this;
1888
- nin(path: string, val: Array<any>): this;
1891
+ nin<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$nin']): this;
1889
1892
 
1890
1893
  /** Specifies arguments for an `$nor` condition. */
1891
1894
  nor(array: Array<FilterQuery<DocType>>): this;
@@ -1921,7 +1924,7 @@ declare module 'mongoose' {
1921
1924
 
1922
1925
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1923
1926
  regex(val: string | RegExp): this;
1924
- regex(path: string, val: string | RegExp): this;
1927
+ regex<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$regex']): this;
1925
1928
 
1926
1929
  /**
1927
1930
  * Declare and/or execute this query as a remove() operation. `remove()` is
@@ -1974,7 +1977,7 @@ declare module 'mongoose' {
1974
1977
 
1975
1978
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
1976
1979
  size(val: number): this;
1977
- size(path: string, val: number): this;
1980
+ size<KEY extends keyof FilterQuery<DocType>>(path: KEY, val: FilterQuery<DocType>[KEY]['$size']): this;
1978
1981
 
1979
1982
  /** Specifies the number of documents to skip. */
1980
1983
  skip(val: number): this;
@@ -2043,7 +2046,7 @@ declare module 'mongoose' {
2043
2046
  wtimeout(ms: number): this;
2044
2047
  }
2045
2048
 
2046
- type ProjectionElementType = number | string;
2049
+ export type ProjectionElementType = number | string;
2047
2050
  export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
2048
2051
 
2049
2052
  export type QuerySelector<T> = {
@@ -2113,10 +2116,10 @@ declare module 'mongoose' {
2113
2116
  [key: string]: any;
2114
2117
  };
2115
2118
 
2116
- type ApplyBasicQueryCasting<T> = T | T[] | any;
2117
- 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>>;
2118
2121
 
2119
- type _FilterQuery<T> = {
2122
+ export type _FilterQuery<T> = {
2120
2123
  [P in keyof T]?: Condition<T[P]>;
2121
2124
  } &
2122
2125
  RootQuerySelector<T>;
@@ -2130,20 +2133,7 @@ declare module 'mongoose' {
2130
2133
  */
2131
2134
  export type FilterQuery<T> = _FilterQuery<T>;
2132
2135
 
2133
- type AddToSetOperators<Type> = {
2134
- $each: Type;
2135
- };
2136
-
2137
- type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2138
-
2139
- type ArrayOperator<Type> = {
2140
- $each: Type;
2141
- $slice?: number;
2142
- $position?: number;
2143
- $sort?: SortValues | Record<string, SortValues>;
2144
- };
2145
-
2146
- type NumericTypes = number | Decimal128 | mongodb.Double | mongodb.Int32 | mongodb.Long;
2136
+ export type SortValues = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
2147
2137
 
2148
2138
  type _UpdateQuery<TSchema> = {
2149
2139
  /** @see https://docs.mongodb.com/manual/reference/operator/update-field/ */
@@ -2170,18 +2160,18 @@ declare module 'mongoose' {
2170
2160
  };
2171
2161
  };
2172
2162
 
2173
- type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2174
- type UpdateAggregationStage = { $addFields: any } |
2163
+ export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
2164
+ export type UpdateAggregationStage = { $addFields: any } |
2175
2165
  { $set: any } |
2176
2166
  { $project: any } |
2177
2167
  { $unset: any } |
2178
2168
  { $replaceRoot: any } |
2179
2169
  { $replaceWith: any };
2180
2170
 
2181
- type __UpdateDefProperty<T> =
2171
+ export type __UpdateDefProperty<T> =
2182
2172
  [Extract<T, mongodb.ObjectId>] extends [never] ? T :
2183
2173
  T | string;
2184
- type _UpdateQueryDef<T> = {
2174
+ export type _UpdateQueryDef<T> = {
2185
2175
  [K in keyof T]?: __UpdateDefProperty<T[K]>;
2186
2176
  };
2187
2177
 
@@ -2209,17 +2199,27 @@ declare module 'mongoose' {
2209
2199
  ? T[K] : FlattenMaps<T[K]>;
2210
2200
  };
2211
2201
 
2212
- type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
2213
- type TreatAsPrimitives = actualPrimitives |
2214
- 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;
2215
2204
 
2216
- type LeanType<T> =
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'>;
2207
+
2208
+ export type LeanType<T> =
2217
2209
  0 extends (1 & T) ? T : // any
2218
2210
  T extends TreatAsPrimitives ? T : // primitives
2219
- T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> : // subdocs
2211
+ T extends Types.Subdocument ? LeanSubdocument<T> : // subdocs
2220
2212
  LeanDocument<T>; // Documents and everything else
2221
2213
 
2222
- 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]>[];
2223
2223
 
2224
2224
  export type _LeanDocument<T> = {
2225
2225
  [K in keyof T]: LeanDocumentElement<T[K]>;
@@ -2228,19 +2228,47 @@ declare module 'mongoose' {
2228
2228
  // Keep this a separate type, to ensure that T is a naked type.
2229
2229
  // This way, the conditional type is distributive over union types.
2230
2230
  // This is required for PopulatedDoc.
2231
- type LeanDocumentElement<T> =
2232
- T extends unknown[] ? LeanArray<T> : // Array
2233
- T extends Document ? LeanDocument<T> : // Subdocument
2234
- 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;
2235
2236
 
2236
2237
  export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
2237
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
+
2238
2265
  /**
2239
2266
  * Documents returned from queries with the lean option enabled.
2240
2267
  * Plain old JavaScript object documents (POJO).
2241
2268
  * @see https://mongoosejs.com/docs/tutorials/lean.html
2242
2269
  */
2243
- 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'>;
2244
2272
 
2245
2273
  export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
2246
2274
  T extends unknown[] ? LeanDocument<T[number]>[] :
@@ -2248,11 +2276,11 @@ declare module 'mongoose' {
2248
2276
  T;
2249
2277
 
2250
2278
  export type LeanDocumentOrArrayWithRawType<T, RawDocType> = 0 extends (1 & T) ? T :
2251
- T extends unknown[] ? RawDocType[] :
2252
- T extends Document ? RawDocType :
2279
+ T extends unknown[] ? LeanDocument<RawDocType>[] :
2280
+ T extends Document ? LeanDocument<RawDocType> :
2253
2281
  T;
2254
2282
 
2255
- class SchemaType {
2283
+ export class SchemaType<T = any> {
2256
2284
  /** SchemaType constructor */
2257
2285
  constructor(path: string, options?: AnyObject, instance?: string);
2258
2286
 
@@ -2268,7 +2296,7 @@ declare module 'mongoose' {
2268
2296
  static get(getter: (value: any) => any): void;
2269
2297
 
2270
2298
  /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
2271
- OptionsConstructor: typeof SchemaTypeOptions;
2299
+ OptionsConstructor: SchemaTypeOptions<T>;
2272
2300
 
2273
2301
  /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
2274
2302
  cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
@@ -2345,14 +2373,14 @@ declare module 'mongoose' {
2345
2373
  continueOnError?: boolean
2346
2374
  }
2347
2375
  export type ConnectionSyncIndexesResult = Record<string, OneCollectionSyncIndexesResult>;
2348
- type OneCollectionSyncIndexesResult = Array<string> & mongodb.MongoServerError;
2349
- 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;
2350
2378
 
2351
- type CallbackWithoutResult = (error: CallbackError) => void;
2352
- type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2379
+ export type CallbackWithoutResult = (error: CallbackError) => void;
2380
+ export type CallbackWithoutResultAndOptionalError = (error?: CallbackError) => void;
2353
2381
 
2354
2382
  /* for ts-mongoose */
2355
- class mquery {}
2356
- }
2383
+ export class mquery { }
2357
2384
 
2358
- export default mongoose;
2385
+ export default mongoose;
2386
+ }