mongoose 6.3.8 → 6.4.1

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
@@ -5,9 +5,10 @@
5
5
  /// <reference path="./cursor.d.ts" />
6
6
  /// <reference path="./document.d.ts" />
7
7
  /// <reference path="./error.d.ts" />
8
+ /// <reference path="./expressions.d.ts" />
8
9
  /// <reference path="./helpers.d.ts" />
9
10
  /// <reference path="./middlewares.d.ts" />
10
- /// <reference path="./indizes.d.ts" />
11
+ /// <reference path="./indexes.d.ts" />
11
12
  /// <reference path="./models.d.ts" />
12
13
  /// <reference path="./mongooseoptions.d.ts" />
13
14
  /// <reference path="./pipelinestage.d.ts" />
@@ -19,6 +20,7 @@
19
20
  /// <reference path="./types.d.ts" />
20
21
  /// <reference path="./utility.d.ts" />
21
22
  /// <reference path="./validation.d.ts" />
23
+ /// <reference path="./inferschematype.d.ts" />
22
24
 
23
25
  declare class NativeDate extends global.Date { }
24
26
 
@@ -61,10 +63,18 @@ declare module 'mongoose' {
61
63
  /* ! ignore */
62
64
  export type CompileModelOptions = { overwriteModels?: boolean, connection?: Connection };
63
65
 
66
+ export function model<TSchema extends Schema = any>(
67
+ name: string,
68
+ schema?: TSchema,
69
+ collection?: string,
70
+ options?: CompileModelOptions
71
+ ): Model<InferSchemaType<TSchema>, ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>, ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>, {}, TSchema> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
72
+
64
73
  export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
74
+
65
75
  export function model<T, U, TQueryHelpers = {}>(
66
76
  name: string,
67
- schema?: Schema<T, U, {}, TQueryHelpers>,
77
+ schema?: Schema<T, any, TQueryHelpers>,
68
78
  collection?: string,
69
79
  options?: CompileModelOptions
70
80
  ): U;
@@ -72,6 +82,12 @@ declare module 'mongoose' {
72
82
  /** Returns an array of model names created on this instance of Mongoose. */
73
83
  export function modelNames(): Array<string>;
74
84
 
85
+ /**
86
+ * Overwrites the current driver used by this Mongoose instance. A driver is a
87
+ * Mongoose-specific interface that defines functions like `find()`.
88
+ */
89
+ export function setDriver(driver: any): Mongoose;
90
+
75
91
  /** The node-mongodb-native driver Mongoose uses. */
76
92
  export const mongo: typeof mongodb;
77
93
 
@@ -91,7 +107,16 @@ declare module 'mongoose' {
91
107
  export interface AnyObject {
92
108
  [k: string]: any
93
109
  }
94
- export type Require_id<T> = T extends { _id?: any } ? (T & { _id: T['_id'] }) : (T & { _id: Types.ObjectId });
110
+
111
+ export type Require_id<T> = T extends { _id?: infer U }
112
+ ? U extends any
113
+ ? (T & { _id: Types.ObjectId })
114
+ : T & Required<{ _id: U }>
115
+ : T & { _id: Types.ObjectId };
116
+
117
+ export type RequireOnlyTypedId<T> = T extends { _id?: infer U; }
118
+ ? Required<{ _id: U }>
119
+ : { _id: Types.ObjectId };
95
120
 
96
121
  export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ? Require_id<DocType> : (Document<unknown, any, DocType> & Require_id<DocType> & TVirtuals & TMethodsAndOverrides);
97
122
 
@@ -131,14 +156,20 @@ declare module 'mongoose' {
131
156
  ? Schema<Omit<DocType, keyof T1> & T1, DiscriminatorModel<T2, M>, T3 | TInstanceMethods, T4 | TQueryHelpers, T5 | TVirtuals>
132
157
  : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals>;
133
158
 
134
- export class Schema<DocType = any, M = Model<DocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}, TVirtuals = any> extends events.EventEmitter {
159
+ type QueryResultType<T> = T extends Query<infer ResultType, any> ? ResultType : never;
160
+
161
+ export class Schema<EnforcedDocType = any, M = Model<EnforcedDocType, any, any, any>, TInstanceMethods = {}, TQueryHelpers = {}, TVirtuals = any,
162
+ TStaticMethods = {},
163
+ TPathTypeKey extends TypeKeyBaseType = DefaultTypeKey,
164
+ DocType extends ObtainDocumentType<DocType, EnforcedDocType, TPathTypeKey> = ObtainDocumentType<any, EnforcedDocType, TPathTypeKey>>
165
+ extends events.EventEmitter {
135
166
  /**
136
167
  * Create a new schema
137
168
  */
138
- constructor(definition?: SchemaDefinition<SchemaDefinitionType<DocType>>, options?: SchemaOptions);
169
+ constructor(definition?: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | DocType, options?: SchemaOptions<TPathTypeKey, DocType, TInstanceMethods, TQueryHelpers, TStaticMethods>);
139
170
 
140
171
  /** Adds key path / schema type pairs to this schema. */
141
- add(obj: SchemaDefinition<SchemaDefinitionType<DocType>> | Schema, prefix?: string): this;
172
+ add(obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | Schema, prefix?: string): this;
142
173
 
143
174
  /**
144
175
  * Array of child schemas (from document arrays and single nested subdocs)
@@ -193,7 +224,7 @@ declare module 'mongoose' {
193
224
  methods: { [F in keyof TInstanceMethods]: TInstanceMethods[F] } & AnyObject;
194
225
 
195
226
  /** The original object passed to the schema constructor */
196
- obj: SchemaDefinition<SchemaDefinitionType<DocType>>;
227
+ obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>>;
197
228
 
198
229
  /** Gets/sets schema paths. */
199
230
  path<ResultType extends SchemaType = SchemaType>(path: string): ResultType;
@@ -211,14 +242,14 @@ declare module 'mongoose' {
211
242
  plugin(fn: (schema: Schema<DocType>, opts?: any) => void, opts?: any): this;
212
243
 
213
244
  /** Defines a post hook for the model. */
214
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T>): this;
215
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
216
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction<T>): this;
217
- post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
218
- post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<any>>): this;
219
- post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<any>>): this;
220
- post<T = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T>): this;
221
- post<T = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T>): this;
245
+ post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T>): this;
246
+ post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
247
+ post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
248
+ post<T extends Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | string | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
249
+ post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
250
+ post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
251
+ post<T = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T, T>): this;
252
+ post<T = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
222
253
 
223
254
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
224
255
  post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
@@ -414,22 +445,20 @@ declare module 'mongoose' {
414
445
  $min?: AnyKeys<TSchema> & AnyObject;
415
446
  $max?: AnyKeys<TSchema> & AnyObject;
416
447
  $mul?: AnyKeys<TSchema> & AnyObject;
417
- $rename?: { [key: string]: string };
448
+ $rename?: Record<string, string>;
418
449
  $set?: AnyKeys<TSchema> & AnyObject;
419
450
  $setOnInsert?: AnyKeys<TSchema> & AnyObject;
420
451
  $unset?: AnyKeys<TSchema> & AnyObject;
421
452
 
422
453
  /** @see https://docs.mongodb.com/manual/reference/operator/update-array/ */
423
- $addToSet?: AnyKeys<TSchema> & AnyObject;
454
+ $addToSet?: mongodb.SetFields<TSchema>;
424
455
  $pop?: AnyKeys<TSchema> & AnyObject;
425
- $pull?: AnyKeys<TSchema> & AnyObject;
426
- $push?: AnyKeys<TSchema> & AnyObject;
427
- $pullAll?: AnyKeys<TSchema> & AnyObject;
456
+ $pull?: mongodb.PullOperator<TSchema>;
457
+ $push?: mongodb.PushOperator<TSchema>;
458
+ $pullAll?: mongodb.PullAllOperator<TSchema>;
428
459
 
429
460
  /** @see https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
430
- $bit?: {
431
- [key: string]: { [key in 'and' | 'or' | 'xor']?: number };
432
- };
461
+ $bit?: Record<string, mongodb.NumericType>;
433
462
  };
434
463
 
435
464
  export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
File without changes
@@ -0,0 +1,155 @@
1
+ import { Schema, InferSchemaType, SchemaType, SchemaTypeOptions, TypeKeyBaseType } from 'mongoose';
2
+
3
+ declare module 'mongoose' {
4
+ /**
5
+ * @summary Obtains document schema type.
6
+ * @description Obtains document schema type from document Definition OR returns enforced schema type if it's provided.
7
+ * @param {DocDefinition} DocDefinition A generic equals to the type of document definition "provided in as first parameter in Schema constructor".
8
+ * @param {EnforcedDocType} EnforcedDocType A generic type enforced by user "provided before schema constructor".
9
+ * @param {TypeKey} TypeKey A generic of literal string type.
10
+ */
11
+ type ObtainDocumentType<DocDefinition, EnforcedDocType = any, TypeKey extends TypeKeyBaseType = DefaultTypeKey> =
12
+ IsItRecordAndNotAny<EnforcedDocType> extends true ? EnforcedDocType : {
13
+ [K in keyof (RequiredPaths<DocDefinition> &
14
+ OptionalPaths<DocDefinition>)]: ObtainDocumentPathType<DocDefinition[K], TypeKey>;
15
+ };
16
+
17
+ /**
18
+ * @summary Obtains document schema type from Schema instance.
19
+ * @param {SchemaType} SchemaType A generic of schema type instance.
20
+ * @example
21
+ * const userSchema = new Schema({userName:String});
22
+ * type UserType = InferSchemaType<typeof userSchema>;
23
+ * // result
24
+ * type UserType = {userName?: string}
25
+ */
26
+ type InferSchemaType<SchemaType> = ObtainSchemaGeneric<SchemaType, 'DocType'> ;
27
+
28
+ /**
29
+ * @summary Obtains schema Generic type by using generic alias.
30
+ * @param {TSchema} TSchema A generic of schema type instance.
31
+ * @param {alias} alias Targeted generic alias.
32
+ */
33
+ type ObtainSchemaGeneric<TSchema, alias extends 'EnforcedDocType' | 'M' | 'TInstanceMethods' | 'TQueryHelpers' | 'TVirtuals' | 'TStaticMethods' | 'TPathTypeKey' | 'DocType'> =
34
+ TSchema extends Schema<infer EnforcedDocType, infer M, infer TInstanceMethods, infer TQueryHelpers, infer TVirtuals, infer TStaticMethods, infer TPathTypeKey, infer DocType>
35
+ ? {
36
+ EnforcedDocType: EnforcedDocType;
37
+ M: M;
38
+ TInstanceMethods: TInstanceMethods;
39
+ TQueryHelpers: TQueryHelpers;
40
+ TVirtuals: TVirtuals;
41
+ TStaticMethods: TStaticMethods;
42
+ TPathTypeKey: TPathTypeKey;
43
+ DocType: DocType;
44
+ }[alias]
45
+ : unknown;
46
+ }
47
+ /**
48
+ * @summary Checks if a type is "Record" or "any".
49
+ * @description It Helps to check if user has provided schema type "EnforcedDocType"
50
+ * @param {T} T A generic type to be checked.
51
+ * @returns true if {@link T} is Record OR false if {@link T} is of any type.
52
+ */
53
+ type IsItRecordAndNotAny<T> = IfEquals<T, any, false, T extends Record<any, any> ? true : false>;
54
+
55
+ /**
56
+ * @summary Checks if two types are identical.
57
+ * @param {T} T The first type to be compared with {@link U}.
58
+ * @param {U} U The seconde type to be compared with {@link T}.
59
+ * @param {Y} Y A type to be returned if {@link T} & {@link U} are identical.
60
+ * @param {N} N A type to be returned if {@link T} & {@link U} are not identical.
61
+ */
62
+ type IfEquals<T, U, Y = true, N = false> =
63
+ (<G>() => G extends T ? 1 : 0) extends
64
+ (<G>() => G extends U ? 1 : 0) ? Y : N;
65
+
66
+ /**
67
+ * @summary Required path base type.
68
+ * @description It helps to check whereas if a path is required OR optional.
69
+ */
70
+ type RequiredPathBaseType = { required: true | [true, string | undefined] };
71
+
72
+ /**
73
+ * @summary Path base type defined by using TypeKey
74
+ * @description It helps to check if a path is defined by TypeKey OR not.
75
+ * @param {TypeKey} TypeKey A literal string refers to path type property key.
76
+ */
77
+ type PathWithTypePropertyBaseType<TypeKey extends TypeKeyBaseType> = { [k in TypeKey]: any };
78
+
79
+ /**
80
+ * @summary A Utility to obtain schema's required path keys.
81
+ * @param {T} T A generic refers to document definition.
82
+ * @returns required paths keys of document definition.
83
+ */
84
+ type RequiredPathKeys<T> = {
85
+ [K in keyof T]: T[K] extends RequiredPathBaseType ? IfEquals<T[K], any, never, K> : never;
86
+ }[keyof T];
87
+
88
+ /**
89
+ * @summary A Utility to obtain schema's required paths.
90
+ * @param {T} T A generic refers to document definition.
91
+ * @returns a record contains required paths with the corresponding type.
92
+ */
93
+ type RequiredPaths<T> = {
94
+ [K in RequiredPathKeys<T>]: T[K];
95
+ };
96
+
97
+ /**
98
+ * @summary A Utility to obtain schema's optional path keys.
99
+ * @param {T} T A generic refers to document definition.
100
+ * @returns optional paths keys of document definition.
101
+ */
102
+ type OptionalPathKeys<T> = {
103
+ [K in keyof T]: T[K] extends RequiredPathBaseType ? never : K;
104
+ }[keyof T];
105
+
106
+ /**
107
+ * @summary A Utility to obtain schema's optional paths.
108
+ * @param {T} T A generic refers to document definition.
109
+ * @returns a record contains optional paths with the corresponding type.
110
+ */
111
+ type OptionalPaths<T> = {
112
+ [K in OptionalPathKeys<T>]?: T[K];
113
+ };
114
+
115
+ /**
116
+ * @summary Obtains schema Path type.
117
+ * @description Obtains Path type by calling {@link ResolvePathType} OR by calling {@link InferSchemaType} if path of schema type.
118
+ * @param {PathValueType} PathValueType Document definition path type.
119
+ * @param {TypeKey} TypeKey A generic refers to document definition.
120
+ */
121
+ type ObtainDocumentPathType<PathValueType, TypeKey extends TypeKeyBaseType> = PathValueType extends Schema<any>
122
+ ? InferSchemaType<PathValueType>
123
+ : ResolvePathType<
124
+ PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? PathValueType[TypeKey] : PathValueType,
125
+ PathValueType extends PathWithTypePropertyBaseType<TypeKey> ? Omit<PathValueType, TypeKey> : {}
126
+ >;
127
+
128
+ /**
129
+ * @param {T} T A generic refers to string path enums.
130
+ * @returns Path enum values type as literal strings or string.
131
+ */
132
+ type PathEnumOrString<T extends SchemaTypeOptions<string>['enum']> = T extends (infer E)[] ? E : T extends { values: any } ? PathEnumOrString<T['values']> : string;
133
+
134
+ /**
135
+ * @summary Resolve path type by returning the corresponding type.
136
+ * @param {PathValueType} PathValueType Document definition path type.
137
+ * @param {Options} Options Document definition path options except path type.
138
+ * @returns Number, "Number" or "number" will be resolved to string type.
139
+ */
140
+ type ResolvePathType<PathValueType, Options extends SchemaTypeOptions<PathValueType> = {}> =
141
+ PathValueType extends (infer Item)[] ? IfEquals<Item, never, any, ResolvePathType<Item>>[] :
142
+ PathValueType extends StringConstructor | 'string' | 'String' | typeof Schema.Types.String ? PathEnumOrString<Options['enum']> :
143
+ PathValueType extends NumberConstructor | 'number' | 'Number' | typeof Schema.Types.Number ? number :
144
+ PathValueType extends DateConstructor | 'date' | 'Date' | typeof Schema.Types.Date ? Date :
145
+ PathValueType extends typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer ? Buffer :
146
+ PathValueType extends BooleanConstructor | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean ? boolean :
147
+ PathValueType extends 'objectId' | 'ObjectId' | typeof Schema.Types.ObjectId ? Schema.Types.ObjectId :
148
+ PathValueType extends 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 ? Schema.Types.Decimal128 :
149
+ PathValueType extends MapConstructor ? Map<string, ResolvePathType<Options['of']>> :
150
+ PathValueType extends ArrayConstructor ? any[] :
151
+ PathValueType extends typeof Schema.Types.Mixed ? any:
152
+ IfEquals<PathValueType, ObjectConstructor> extends true ? any:
153
+ IfEquals<PathValueType, {}> extends true ? any:
154
+ PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
155
+ unknown;
package/types/models.d.ts CHANGED
@@ -114,12 +114,12 @@ declare module 'mongoose' {
114
114
  }
115
115
 
116
116
  const Model: Model<any>;
117
- interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}> extends
117
+ interface Model<T, TQueryHelpers = {}, TMethodsAndOverrides = {}, TVirtuals = {}, TSchema = any> extends
118
118
  NodeJS.EventEmitter,
119
119
  AcceptsDiscriminator,
120
120
  IndexManager,
121
121
  SessionStarter {
122
- new <DocType = AnyKeys<T> & AnyObject>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
122
+ new <DocType = T>(doc?: DocType, fields?: any | null, options?: boolean | AnyObject): HydratedDocument<T, TMethodsAndOverrides, TVirtuals> & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
123
123
 
124
124
  aggregate<R = any>(pipeline?: PipelineStage[], options?: mongodb.AggregateOptions, callback?: Callback<R[]>): Aggregate<Array<R>>;
125
125
  aggregate<R = any>(pipeline: PipelineStage[], callback?: Callback<R[]>): Aggregate<Array<R>>;
@@ -128,27 +128,27 @@ declare module 'mongoose' {
128
128
  base: Mongoose;
129
129
 
130
130
  /**
131
- * If this is a discriminator model, `baseModelName` is the name of
132
- * the base model.
133
- */
131
+ * If this is a discriminator model, `baseModelName` is the name of
132
+ * the base model.
133
+ */
134
134
  baseModelName: string | undefined;
135
135
 
136
136
  /**
137
- * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
138
- * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
139
- * command. This is faster than sending multiple independent operations (e.g.
140
- * if you use `create()`) because with `bulkWrite()` there is only one network
141
- * round trip to the MongoDB server.
142
- */
137
+ * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`,
138
+ * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one
139
+ * command. This is faster than sending multiple independent operations (e.g.
140
+ * if you use `create()`) because with `bulkWrite()` there is only one network
141
+ * round trip to the MongoDB server.
142
+ */
143
143
  bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation>, options: mongodb.BulkWriteOptions & MongooseBulkWriteOptions, callback: Callback<mongodb.BulkWriteResult>): void;
144
144
  bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation>, callback: Callback<mongodb.BulkWriteResult>): void;
145
145
  bulkWrite(writes: Array<mongodb.AnyBulkWriteOperation>, options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions): Promise<mongodb.BulkWriteResult>;
146
146
 
147
147
  /**
148
- * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than
149
- * sending multiple `save()` calls because with `bulkSave()` there is only one
150
- * network round trip to the MongoDB server.
151
- */
148
+ * Sends multiple `save()` calls in a single `bulkWrite()`. This is faster than
149
+ * sending multiple `save()` calls because with `bulkSave()` there is only one
150
+ * network round trip to the MongoDB server.
151
+ */
152
152
  bulkSave(documents: Array<Document>, options?: mongodb.BulkWriteOptions): Promise<mongodb.BulkWriteResult>;
153
153
 
154
154
  /** Collection the model uses. */
@@ -163,21 +163,17 @@ declare module 'mongoose' {
163
163
  countDocuments(callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
164
164
 
165
165
  /** Creates a new document or documents */
166
- create(docs: (AnyKeys<T> | AnyObject)[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
167
- create(docs: (AnyKeys<T> | AnyObject)[], callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>): void;
168
- create(doc: AnyKeys<T> | AnyObject): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
169
- create(doc: AnyKeys<T> | AnyObject, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): void;
170
- create<DocContents = AnyKeys<T>>(docs: DocContents[], options?: SaveOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
171
- create<DocContents = AnyKeys<T>>(docs: DocContents[], callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>): void;
172
- create<DocContents = AnyKeys<T>>(doc: DocContents): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
173
- create<DocContents = AnyKeys<T>>(...docs: DocContents[]): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
174
- create<DocContents = AnyKeys<T>>(doc: DocContents, callback: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>): void;
166
+ create<DocContents = T>(docs: Array<T | DocContents>, options?: SaveOptions): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>;
167
+ create<DocContents = T>(docs: Array<T | DocContents>, callback: Callback<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>): void;
168
+ create<DocContents = T>(doc: DocContents | T): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>;
169
+ create<DocContents = T>(...docs: Array<T | DocContents>): Promise<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>[]>;
170
+ create<DocContents = T>(doc: T | DocContents, callback: Callback<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>): void;
175
171
 
176
172
  /**
177
- * Create the collection for this model. By default, if no indexes are specified,
178
- * mongoose will not create the collection for the model until any documents are
179
- * created. Use this method to create the collection explicitly.
180
- */
173
+ * Create the collection for this model. By default, if no indexes are specified,
174
+ * mongoose will not create the collection for the model until any documents are
175
+ * created. Use this method to create the collection explicitly.
176
+ */
181
177
  createCollection<T extends mongodb.Document>(options: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'> | null, callback: Callback<mongodb.Collection<T>>): void;
182
178
  createCollection<T extends mongodb.Document>(callback: Callback<mongodb.Collection<T>>): void;
183
179
  createCollection<T extends mongodb.Document>(options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>): Promise<mongodb.Collection<T>>;
@@ -186,34 +182,34 @@ declare module 'mongoose' {
186
182
  db: Connection;
187
183
 
188
184
  /**
189
- * Deletes all of the documents that match `conditions` from the collection.
190
- * Behaves like `remove()`, but deletes all documents that match `conditions`
191
- * regardless of the `single` option.
192
- */
185
+ * Deletes all of the documents that match `conditions` from the collection.
186
+ * Behaves like `remove()`, but deletes all documents that match `conditions`
187
+ * regardless of the `single` option.
188
+ */
193
189
  deleteMany(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
194
190
  deleteMany(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
195
191
  deleteMany(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
196
192
 
197
193
  /**
198
- * Deletes the first document that matches `conditions` from the collection.
199
- * Behaves like `remove()`, but deletes at most one document regardless of the
200
- * `single` option.
201
- */
194
+ * Deletes the first document that matches `conditions` from the collection.
195
+ * Behaves like `remove()`, but deletes at most one document regardless of the
196
+ * `single` option.
197
+ */
202
198
  deleteOne(filter?: FilterQuery<T>, options?: QueryOptions<T>, callback?: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
203
199
  deleteOne(filter: FilterQuery<T>, callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
204
200
  deleteOne(callback: CallbackWithoutResult): QueryWithHelpers<mongodb.DeleteResult, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
205
201
 
206
202
  /**
207
- * Event emitter that reports any errors that occurred. Useful for global error
208
- * handling.
209
- */
203
+ * Event emitter that reports any errors that occurred. Useful for global error
204
+ * handling.
205
+ */
210
206
  events: NodeJS.EventEmitter;
211
207
 
212
208
  /**
213
- * Finds a single document by its _id field. `findById(id)` is almost*
214
- * equivalent to `findOne({ _id: id })`. If you want to query by a document's
215
- * `_id`, use `findById()` instead of `findOne()`.
216
- */
209
+ * Finds a single document by its _id field. `findById(id)` is almost*
210
+ * equivalent to `findOne({ _id: id })`. If you want to query by a document's
211
+ * `_id`, use `findById()` instead of `findOne()`.
212
+ */
217
213
  findById<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
218
214
  id: any,
219
215
  projection?: ProjectionType<T> | null,
@@ -244,28 +240,37 @@ declare module 'mongoose' {
244
240
  ): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
245
241
 
246
242
  /**
247
- * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
248
- * The document returned has no paths marked as modified initially.
249
- */
243
+ * Shortcut for creating a new Document from existing raw data, pre-saved in the DB.
244
+ * The document returned has no paths marked as modified initially.
245
+ */
250
246
  hydrate(obj: any): HydratedDocument<T, TMethodsAndOverrides, TVirtuals>;
251
247
 
252
248
  /**
253
- * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
254
- * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
255
- * Mongoose calls this function automatically when a model is created using
256
- * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
257
- * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
258
- * don't need to call it.
259
- */
249
+ * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/),
250
+ * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off.
251
+ * Mongoose calls this function automatically when a model is created using
252
+ * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or
253
+ * [`connection.model()`](/docs/api.html#connection_Connection-model), so you
254
+ * don't need to call it.
255
+ */
260
256
  init(callback?: CallbackWithoutResult): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>;
261
257
 
262
258
  /** Inserts one or more new documents as a single `insertMany` call to the MongoDB server. */
263
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult<T>>;
264
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options?: InsertManyOptions): Promise<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>>;
265
- insertMany(doc: AnyKeys<T> | AnyObject, options: InsertManyOptions & { rawResult: true }): Promise<InsertManyResult<T>>;
266
- insertMany(doc: AnyKeys<T> | AnyObject, options?: InsertManyOptions): Promise<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[]>;
267
- insertMany(doc: AnyKeys<T> | AnyObject, options?: InsertManyOptions, callback?: Callback<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>[] | InsertManyResult<T>>): void;
268
- insertMany(docs: Array<AnyKeys<T> | AnyObject>, options?: InsertManyOptions, callback?: Callback<Array<HydratedDocument<T, TMethodsAndOverrides, TVirtuals>> | InsertManyResult<T>>): void;
259
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>): void;
260
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { rawResult: true; }, callback: Callback<mongodb.InsertManyResult<T>>): void;
261
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
262
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }, callback: Callback<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>): void;
263
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { rawResult: true; }, callback: Callback<mongodb.InsertManyResult<T>>): void;
264
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean?: false | undefined }, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
265
+ insertMany<DocContents = T>(doc: DocContents, callback: Callback<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>): void;
266
+
267
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>;
268
+ insertMany<DocContents = T>(docs: Array<DocContents | T>, options: InsertManyOptions & { rawResult: true; }): Promise<mongodb.InsertManyResult<T>>;
269
+ insertMany<DocContents = T>(docs: Array<DocContents | T>): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
270
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { lean: true; }): Promise<Array<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>>>;
271
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions & { rawResult: true; }): Promise<mongodb.InsertManyResult<T>>;
272
+ insertMany<DocContents = T>(doc: DocContents, options: InsertManyOptions): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
273
+ insertMany<DocContents = T>(doc: DocContents): Promise<Array<HydratedDocument<MergeType<MergeType<T, DocContents>, RequireOnlyTypedId<T>>, TMethodsAndOverrides, TVirtuals>>>;
269
274
 
270
275
  /** The name of the model */
271
276
  modelName: string;
@@ -301,21 +306,31 @@ declare module 'mongoose' {
301
306
  estimatedDocumentCount(options?: QueryOptions<T>, callback?: Callback<number>): QueryWithHelpers<number, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
302
307
 
303
308
  /**
304
- * Returns a document with its `_id` if at least one document exists in the database that matches
305
- * the given `filter`, and `null` otherwise.
306
- */
309
+ * Returns a document with its `_id` if at least one document exists in the database that matches
310
+ * the given `filter`, and `null` otherwise.
311
+ */
307
312
  exists(filter: FilterQuery<T>, callback: Callback<Pick<Document<T>, '_id'> | null>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
308
313
  exists(filter: FilterQuery<T>): QueryWithHelpers<Pick<Document<T>, '_id'> | null, HydratedDocument<T, TMethodsAndOverrides, TVirtuals>, TQueryHelpers, T>;
309
314
 
310
315
  /** Creates a `find` query: gets a list of documents that match `filter`. */
311
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
312
316
  find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
313
317
  filter: FilterQuery<T>,
314
- projection?: ProjectionType<T> | null,
315
- callback?: Callback<ResultDoc[]>
318
+ projection?: ProjectionType<T> | null | undefined,
319
+ options?: QueryOptions<T> | null | undefined,
320
+ callback?: Callback<ResultDoc[]> | undefined
321
+ ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
322
+ find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
323
+ filter: FilterQuery<T>,
324
+ projection?: ProjectionType<T> | null | undefined,
325
+ callback?: Callback<ResultDoc[]> | undefined
326
+ ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
327
+ find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
328
+ filter: FilterQuery<T>,
329
+ callback?: Callback<ResultDoc[]> | undefined
330
+ ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
331
+ find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
332
+ callback?: Callback<ResultDoc[]> | undefined
316
333
  ): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
317
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
318
- find<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(filter: FilterQuery<T>, projection?: ProjectionType<T> | null, options?: QueryOptions<T> | null, callback?: Callback<ResultDoc[]>): QueryWithHelpers<Array<ResultDoc>, ResultDoc, TQueryHelpers, T>;
319
334
 
320
335
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
321
336
  findByIdAndDelete<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(id?: mongodb.ObjectId | any, options?: QueryOptions<T> | null, callback?: (err: CallbackError, doc: ResultDoc | null, res: any) => void): QueryWithHelpers<ResultDoc | null, ResultDoc, TQueryHelpers, T>;
@@ -385,9 +400,9 @@ declare module 'mongoose' {
385
400
  schema: Schema<T>;
386
401
 
387
402
  /**
388
- * @deprecated use `updateOne` or `updateMany` instead.
389
- * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
390
- */
403
+ * @deprecated use `updateOne` or `updateMany` instead.
404
+ * Creates a `update` query: updates one or many documents that match `filter` with `update`, based on the `multi` option.
405
+ */
391
406
  update<ResultDoc = HydratedDocument<T, TMethodsAndOverrides, TVirtuals>>(
392
407
  filter?: FilterQuery<T>,
393
408
  update?: UpdateQuery<T> | UpdateWithAggregationPipeline,
@@ -79,6 +79,14 @@ declare module 'mongoose' {
79
79
  | stream.Writable
80
80
  | ((collectionName: string, methodName: string, ...methodArgs: any[]) => void);
81
81
 
82
+ /**
83
+ * If `false`, it will change the `createdAt` field to be [`immutable: false`](https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-immutable)
84
+ * which means you can update the `createdAt`.
85
+ *
86
+ * @default true
87
+ */
88
+ 'timestamps.createdAt.immutable'?: boolean
89
+
82
90
  /** If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query */
83
91
  maxTimeMS?: number;
84
92