UNPKG

36.9 kBTypeScriptView Raw
1/// <reference path="./aggregate.d.ts" />
2/// <reference path="./callback.d.ts" />
3/// <reference path="./collection.d.ts" />
4/// <reference path="./connection.d.ts" />
5/// <reference path="./cursor.d.ts" />
6/// <reference path="./document.d.ts" />
7/// <reference path="./error.d.ts" />
8/// <reference path="./expressions.d.ts" />
9/// <reference path="./helpers.d.ts" />
10/// <reference path="./middlewares.d.ts" />
11/// <reference path="./indexes.d.ts" />
12/// <reference path="./models.d.ts" />
13/// <reference path="./mongooseoptions.d.ts" />
14/// <reference path="./pipelinestage.d.ts" />
15/// <reference path="./populate.d.ts" />
16/// <reference path="./query.d.ts" />
17/// <reference path="./schemaoptions.d.ts" />
18/// <reference path="./schematypes.d.ts" />
19/// <reference path="./session.d.ts" />
20/// <reference path="./types.d.ts" />
21/// <reference path="./utility.d.ts" />
22/// <reference path="./validation.d.ts" />
23/// <reference path="./inferschematype.d.ts" />
24/// <reference path="./virtuals.d.ts" />
25/// <reference path="./augmentations.d.ts" />
26
27declare class NativeDate extends global.Date { }
28
29declare module 'mongoose' {
30 import events = require('events');
31 import mongodb = require('mongodb');
32 import mongoose = require('mongoose');
33
34 export type Mongoose = typeof mongoose;
35
36 /**
37 * Mongoose constructor. The exports object of the `mongoose` module is an instance of this
38 * class. Most apps will only use this one instance.
39 */
40 export const Mongoose: new (options?: MongooseOptions | null) => Mongoose;
41
42 export let Promise: any;
43
44 /**
45 * Can be extended to explicitly type specific models.
46 */
47 export interface Models {
48 [modelName: string]: Model<any>
49 }
50
51 /** An array containing all models associated with this Mongoose instance. */
52 export const models: Models;
53
54 /**
55 * Removes the model named `name` from the default connection, if it exists.
56 * You can use this function to clean up any models you created in your tests to
57 * prevent OverwriteModelErrors.
58 */
59 export function deleteModel(name: string | RegExp): Mongoose;
60
61 /**
62 * Sanitizes query filters against query selector injection attacks by wrapping
63 * any nested objects that have a property whose name starts with `$` in a `$eq`.
64 */
65 export function sanitizeFilter<T>(filter: FilterQuery<T>): FilterQuery<T>;
66
67 /** Gets mongoose options */
68 export function get<K extends keyof MongooseOptions>(key: K): MongooseOptions[K];
69
70 /* ! ignore */
71 export type CompileModelOptions = {
72 overwriteModels?: boolean,
73 connection?: Connection
74 };
75
76 export function model<TSchema extends Schema = any>(
77 name: string,
78 schema?: TSchema,
79 collection?: string,
80 options?: CompileModelOptions
81 ): Model<
82 InferSchemaType<TSchema>,
83 ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
84 ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
85 ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
86 HydratedDocument<
87 InferSchemaType<TSchema>,
88 ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
89 ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>
90 >,
91 TSchema
92 > & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
93
94 export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
95
96 export function model<T, U, TQueryHelpers = {}>(
97 name: string,
98 schema?: Schema<T, any, any, TQueryHelpers, any, any, any>,
99 collection?: string,
100 options?: CompileModelOptions
101 ): U;
102
103 /** Returns an array of model names created on this instance of Mongoose. */
104 export function modelNames(): Array<string>;
105
106 /**
107 * Overwrites the current driver used by this Mongoose instance. A driver is a
108 * Mongoose-specific interface that defines functions like `find()`.
109 */
110 export function setDriver(driver: any): Mongoose;
111
112 /** The node-mongodb-native driver Mongoose uses. */
113 export { mongodb as mongo };
114
115 /** Declares a global plugin executed on all Schemas. */
116 export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose;
117
118 /** Getter/setter around function for pluralizing collection names. */
119 export function pluralize(fn?: ((str: string) => string) | null): ((str: string) => string) | null;
120
121 /** Sets mongoose options */
122 export function set<K extends keyof MongooseOptions>(key: K, value: MongooseOptions[K]): Mongoose;
123 export function set(options: { [K in keyof MongooseOptions]: MongooseOptions[K] }): Mongoose;
124
125 /** The Mongoose version */
126 export const version: string;
127
128 export type AnyKeys<T> = { [P in keyof T]?: T[P] | any };
129 export interface AnyObject {
130 [k: string]: any
131 }
132
133 export type Require_id<T> = T extends { _id?: infer U }
134 ? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
135 : T & { _id: Types.ObjectId };
136
137 /** Helper type for getting the hydrated document type from the raw document type. The hydrated document type is what `new MyModel()` returns. */
138 export type HydratedDocument<
139 DocType,
140 TOverrides = {},
141 TQueryHelpers = {}
142 > = IfAny<
143 DocType,
144 any,
145 TOverrides extends Record<string, never> ?
146 Document<unknown, TQueryHelpers, DocType> & Require_id<DocType> :
147 IfAny<
148 TOverrides,
149 Document<unknown, TQueryHelpers, DocType> & Require_id<DocType>,
150 Document<unknown, TQueryHelpers, DocType> & MergeType<
151 Require_id<DocType>,
152 TOverrides
153 >
154 >
155 >;
156 export type HydratedSingleSubdocument<DocType, TOverrides = {}> = Types.Subdocument<unknown> & Require_id<DocType> & TOverrides;
157 export type HydratedArraySubdocument<DocType, TOverrides = {}> = Types.ArraySubdocument<unknown> & Require_id<DocType> & TOverrides;
158
159 export type HydratedDocumentFromSchema<TSchema extends Schema> = HydratedDocument<
160 InferSchemaType<TSchema>,
161 ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
162 ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>
163 >;
164
165 export interface TagSet {
166 [k: string]: string;
167 }
168
169 export interface ToObjectOptions<THydratedDocumentType = HydratedDocument<unknown>> {
170 /** apply all getters (path and virtual getters) */
171 getters?: boolean;
172 /** apply virtual getters (can override getters option) */
173 virtuals?: boolean | string[];
174 /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */
175 aliases?: boolean;
176 /** remove empty objects (defaults to true) */
177 minimize?: boolean;
178 /** if set, mongoose will call this function to allow you to transform the returned object */
179 transform?: boolean | ((
180 doc: THydratedDocumentType,
181 ret: Record<string, any>,
182 options: ToObjectOptions<THydratedDocumentType>
183 ) => any);
184 /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */
185 depopulate?: boolean;
186 /** if false, exclude the version key (`__v` by default) from the output */
187 versionKey?: boolean;
188 /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */
189 flattenMaps?: boolean;
190 /** if true, convert any ObjectIds in the result to 24 character hex strings. */
191 flattenObjectIds?: boolean;
192 /** If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. */
193 useProjection?: boolean;
194 }
195
196 export type DiscriminatorModel<M, T> = T extends Model<infer T, infer TQueryHelpers, infer TInstanceMethods, infer TVirtuals>
197 ?
198 M extends Model<infer M, infer MQueryHelpers, infer MInstanceMethods, infer MVirtuals>
199 ? Model<Omit<M, keyof T> & T, MQueryHelpers | TQueryHelpers, MInstanceMethods | TInstanceMethods, MVirtuals | TVirtuals>
200 : M
201 : M;
202
203 export type DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods, DisSchema> =
204 DisSchema extends Schema<infer DisSchemaEDocType, infer DisSchemaM, infer DisSchemaInstanceMethods, infer DisSchemaQueryhelpers, infer DisSchemaVirtuals, infer DisSchemaStatics>
205 ? Schema<MergeType<DocType, DisSchemaEDocType>, DiscriminatorModel<DisSchemaM, M>, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods>
206 : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>;
207
208 type QueryResultType<T> = T extends Query<infer ResultType, any> ? ResultType : never;
209
210 type PluginFunction<
211 DocType,
212 M,
213 TInstanceMethods,
214 TQueryHelpers,
215 TVirtuals,
216 TStaticMethods> = (schema: Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>, opts?: any) => void;
217
218 export class Schema<
219 EnforcedDocType = any,
220 TModelType = Model<EnforcedDocType, any, any, any>,
221 TInstanceMethods = {},
222 TQueryHelpers = {},
223 TVirtuals = {},
224 TStaticMethods = {},
225 TSchemaOptions = DefaultSchemaOptions,
226 DocType extends ApplySchemaOptions<
227 ObtainDocumentType<DocType, EnforcedDocType, ResolveSchemaOptions<TSchemaOptions>>,
228 ResolveSchemaOptions<TSchemaOptions>
229 > = ApplySchemaOptions<
230 ObtainDocumentType<any, EnforcedDocType, ResolveSchemaOptions<TSchemaOptions>>,
231 ResolveSchemaOptions<TSchemaOptions>
232 >,
233 THydratedDocumentType = HydratedDocument<FlatRecord<DocType>, TVirtuals & TInstanceMethods>
234 >
235 extends events.EventEmitter {
236 /**
237 * Create a new schema
238 */
239 constructor(definition?: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>, EnforcedDocType> | DocType, options?: SchemaOptions<FlatRecord<DocType>, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals, THydratedDocumentType> | ResolveSchemaOptions<TSchemaOptions>);
240
241 /** Adds key path / schema type pairs to this schema. */
242 add(obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | Schema, prefix?: string): this;
243
244 /**
245 * Add an alias for `path`. This means getting or setting the `alias`
246 * is equivalent to getting or setting the `path`.
247 */
248 alias(path: string, alias: string | string[]): this;
249
250 /**
251 * Array of child schemas (from document arrays and single nested subdocs)
252 * and their corresponding compiled models. Each element of the array is
253 * an object with 2 properties: `schema` and `model`.
254 */
255 childSchemas: { schema: Schema, model: any }[];
256
257 /** Removes all indexes on this schema */
258 clearIndexes(): this;
259
260 /** Returns a copy of this schema */
261 clone<T = this>(): T;
262
263 discriminator<DisSchema = Schema>(name: string | number, schema: DisSchema): this;
264
265 /** Returns a new schema that has the picked `paths` from this schema. */
266 pick<T = this>(paths: string[], options?: SchemaOptions): T;
267
268 /** Object containing discriminators defined on this schema */
269 discriminators?: { [name: string]: Schema };
270
271 /** Iterates the schemas paths similar to Array#forEach. */
272 eachPath(fn: (path: string, type: SchemaType) => void): this;
273
274 /** Defines an index (most likely compound) for this schema. */
275 index(fields: IndexDefinition, options?: IndexOptions): this;
276
277 /**
278 * Define a search index for this schema.
279 *
280 * @remarks Search indexes are only supported when used against a 7.0+ Mongo Atlas cluster.
281 */
282 searchIndex(description: mongodb.SearchIndexDescription): this;
283
284 /**
285 * Returns a list of indexes that this schema declares, via `schema.index()`
286 * or by `index: true` in a path's options.
287 */
288 indexes(): Array<[IndexDefinition, IndexOptions]>;
289
290 /** Gets a schema option. */
291 get<K extends keyof SchemaOptions>(key: K): SchemaOptions[K];
292
293 /**
294 * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
295 * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
296 * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
297 * [statics](http://mongoosejs.com/docs/guide.html#statics), and
298 * [methods](http://mongoosejs.com/docs/guide.html#methods).
299 */
300 loadClass(model: Function, onlyVirtuals?: boolean): this;
301
302 /** Adds an instance method to documents constructed from Models compiled from this schema. */
303 method<Context = THydratedDocumentType>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
304 method(obj: Partial<TInstanceMethods>): this;
305
306 /** Object of currently defined methods on this schema. */
307 methods: AddThisParameter<TInstanceMethods, THydratedDocumentType> & AnyObject;
308
309 /** The original object passed to the schema constructor */
310 obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>, EnforcedDocType>;
311
312 /** Returns a new schema that has the `paths` from the original schema, minus the omitted ones. */
313 omit<T = this>(paths: string[], options?: SchemaOptions): T;
314
315 /** Gets/sets schema paths. */
316 path<ResultType extends SchemaType = SchemaType<any, THydratedDocumentType>>(path: string): ResultType;
317 path<pathGeneric extends keyof EnforcedDocType>(path: pathGeneric): SchemaType<EnforcedDocType[pathGeneric]>;
318 path(path: string, constructor: any): this;
319
320 /** Lists all paths and their type in the schema. */
321 paths: {
322 [key: string]: SchemaType;
323 };
324
325 /** Returns the pathType of `path` for this schema. */
326 pathType(path: string): string;
327
328 /** Registers a plugin for this schema. */
329 plugin<PFunc extends PluginFunction<DocType, TModelType, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
330
331 /** Defines a post hook for the model. */
332
333 // PostMiddlewareFunction
334 // with errorHandler set to true
335 post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
336 post<T = THydratedDocumentType>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
337 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T, Array<any>>): this;
338 post<T = TModelType>(method: 'insertMany' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
339
340 // this = never since it never happens
341 post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: PostMiddlewareFunction<never, never>): this;
342 post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
343 post<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, T>): this;
344 // this = Document
345 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PostMiddlewareFunction<T, T>): this;
346 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
347 post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: PostMiddlewareFunction<T, T>): this;
348 // this = Query
349 post<T = Query<any, any>>(method: MongooseRawResultQueryMiddleware|MongooseRawResultQueryMiddleware[], fn: PostMiddlewareFunction<T, null | QueryResultType<T> | ModifyResult<QueryResultType<T>>>): this;
350 post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
351 post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
352 post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
353 // this = Union of Document and Query, could be called with any of them
354 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
355 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
356
357 // ErrorHandlingMiddlewareFunction
358 // this = never since it never happens
359 post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
360 post<T = never>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & { document: false, query: boolean }, fn: ErrorHandlingMiddlewareFunction<T>): this;
361 post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
362 // this = Document
363 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
364 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
365 post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
366 // this = Query
367 post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
368 post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
369 post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
370 // this = Union of Document and Query, could be called with any of them
371 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
372 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
373
374 // method aggregate and insertMany with PostMiddlewareFunction
375 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
376 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
377 post<T = TModelType>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T, T>): this;
378 post<T = TModelType>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
379
380 // method aggregate and insertMany with ErrorHandlingMiddlewareFunction
381 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
382 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
383 post<T = TModelType>(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
384 post<T = TModelType>(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
385
386 /** Defines a pre hook for the model. */
387 // this = never since it never happens
388 pre<T = never>(method: 'save', options: SchemaPreOptions & { document: false, query: boolean }, fn: PreSaveMiddlewareFunction<T>): this;
389 pre<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: false }, fn: PreMiddlewareFunction<T>): this;
390 pre<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions & { document: boolean, query: false }, fn: PreMiddlewareFunction<T>): this;
391 pre<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: boolean }, fn: PreMiddlewareFunction<T>): this;
392 // this = Union of Document and Query, could be called with any of them
393 pre<T = THydratedDocumentType | Query<any, any>>(
394 method: MongooseQueryAndDocumentMiddleware | MongooseQueryAndDocumentMiddleware[] | RegExp,
395 options: SchemaPreOptions & { document: true, query: true },
396 fn: PreMiddlewareFunction<T>
397 ): this;
398 // this = Document
399 pre<T = THydratedDocumentType>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
400 pre<T = THydratedDocumentType>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction<T>): this;
401 pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PreMiddlewareFunction<T>): this;
402 pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
403 pre<T = THydratedDocumentType>(
404 method: MongooseQueryAndDocumentMiddleware | MongooseQueryAndDocumentMiddleware[] | RegExp,
405 options: SchemaPreOptions & { document: true },
406 fn: PreMiddlewareFunction<T>
407 ): this;
408 pre<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: false }, fn: PreMiddlewareFunction<T>): this;
409 // this = Query
410 pre<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PreMiddlewareFunction<T>): this;
411 pre<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
412 pre<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: true }, fn: PreMiddlewareFunction<T>): this;
413 // this = Union of Document and Query, could be called with any of them
414 pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreMiddlewareFunction<T>): this;
415 pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
416 // method aggregate
417 pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
418 pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
419 /* method insertMany */
420 pre<T = TModelType>(
421 method: 'insertMany' | RegExp,
422 fn: (
423 this: T,
424 next: (err?: CallbackError) => void,
425 docs: any | Array<any>,
426 options?: InsertManyOptions & { lean?: boolean }
427 ) => void | Promise<void>
428 ): this;
429 pre<T = TModelType>(
430 method: 'insertMany' | RegExp,
431 options: SchemaPreOptions,
432 fn: (
433 this: T,
434 next: (err?: CallbackError) => void,
435 docs: any | Array<any>,
436 options?: InsertManyOptions & { lean?: boolean }
437 ) => void | Promise<void>
438 ): this;
439 /* method bulkWrite */
440 pre<T = TModelType>(
441 method: 'bulkWrite' | RegExp,
442 fn: (
443 this: T,
444 next: (err?: CallbackError) => void,
445 ops: Array<mongodb.AnyBulkWriteOperation<any> & MongooseBulkWritePerWriteOptions>,
446 options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions
447 ) => void | Promise<void>
448 ): this;
449 pre<T = TModelType>(
450 method: 'bulkWrite' | RegExp,
451 options: SchemaPreOptions,
452 fn: (
453 this: T,
454 next: (err?: CallbackError) => void,
455 ops: Array<mongodb.AnyBulkWriteOperation<any> & MongooseBulkWritePerWriteOptions>,
456 options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions
457 ) => void | Promise<void>
458 ): this;
459 /* method createCollection */
460 pre<T = TModelType>(
461 method: 'createCollection' | RegExp,
462 fn: (
463 this: T,
464 next: (err?: CallbackError) => void,
465 options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>
466 ) => void | Promise<void>
467 ): this;
468 pre<T = TModelType>(
469 method: 'createCollection' | RegExp,
470 options: SchemaPreOptions,
471 fn: (
472 this: T,
473 next: (err?: CallbackError) => void,
474 options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>
475 ) => void | Promise<void>
476 ): this;
477
478 /** Object of currently defined query helpers on this schema. */
479 query: TQueryHelpers;
480
481 /** Adds a method call to the queue. */
482 queue(name: string, args: any[]): this;
483
484 /** Removes the given `path` (or [`paths`]). */
485 remove(paths: string | Array<string>): this;
486
487 /** Removes index by name or index spec */
488 remove(index: string | AnyObject): this;
489
490 /** Returns an Array of path strings that are required by this schema. */
491 requiredPaths(invalidate?: boolean): string[];
492
493 /** Sets a schema option. */
494 set<K extends keyof SchemaOptions>(key: K, value: SchemaOptions[K], _tags?: any): this;
495
496 /** Adds static "class" methods to Models compiled from this schema. */
497 static<K extends keyof TStaticMethods>(name: K, fn: TStaticMethods[K]): this;
498 static(obj: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: TModelType, ...args: any[]) => any }): this;
499 static(name: string, fn: (this: TModelType, ...args: any[]) => any): this;
500
501 /** Object of currently defined statics on this schema. */
502 statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } &
503 { [name: string]: (this: TModelType, ...args: any[]) => unknown };
504
505 /** Creates a virtual type with the given name. */
506 virtual<T = HydratedDocument<DocType, TVirtuals & TInstanceMethods, TQueryHelpers>>(
507 name: keyof TVirtuals | string,
508 options?: VirtualTypeOptions<T, DocType>
509 ): VirtualType<T>;
510
511 /** Object of currently defined virtuals on this schema */
512 virtuals: TVirtuals;
513
514 /** Returns the virtual type with the given `name`. */
515 virtualpath<T = THydratedDocumentType>(name: string): VirtualType<T> | null;
516
517 static ObjectId: typeof Schema.Types.ObjectId;
518 }
519
520 export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
521 export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
522 export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
523 export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
524 export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
525
526 export type SchemaDefinitionWithBuiltInClass<T> = T extends number
527 ? NumberSchemaDefinition
528 : T extends string
529 ? StringSchemaDefinition
530 : T extends boolean
531 ? BooleanSchemaDefinition
532 : T extends NativeDate
533 ? DateSchemaDefinition
534 : (Function | string);
535
536 export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any> = SchemaDefinitionWithBuiltInClass<T> |
537 SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType> |
538 typeof SchemaType |
539 Schema<any, any, any> |
540 Schema<any, any, any>[] |
541 SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType>[] |
542 Function[] |
543 SchemaDefinition<T, EnforcedDocType> |
544 SchemaDefinition<Unpacked<T>, EnforcedDocType>[] |
545 typeof Schema.Types.Mixed |
546 MixedSchemaTypeOptions<EnforcedDocType>;
547
548 export type SchemaDefinition<T = undefined, EnforcedDocType = any> = T extends undefined
549 ? { [path: string]: SchemaDefinitionProperty; }
550 : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType>; };
551
552 export type AnyArray<T> = T[] | ReadonlyArray<T>;
553 export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
554
555 export interface MixedSchemaTypeOptions<EnforcedDocType> extends SchemaTypeOptions<Schema.Types.Mixed, EnforcedDocType> {
556 type: typeof Schema.Types.Mixed;
557 }
558
559 export type RefType =
560 | number
561 | string
562 | Buffer
563 | undefined
564 | Types.ObjectId
565 | Types.Buffer
566 | typeof Schema.Types.Number
567 | typeof Schema.Types.String
568 | typeof Schema.Types.Buffer
569 | typeof Schema.Types.ObjectId;
570
571
572 export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
573
574 export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
575 /** If `ref` is not nullish, this becomes a populated virtual. */
576 ref?: string | Function;
577
578 /** The local field to populate on if this is a populated virtual. */
579 localField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
580
581 /** The foreign field to populate on if this is a populated virtual. */
582 foreignField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
583
584 /**
585 * By default, a populated virtual is an array. If you set `justOne`,
586 * the populated virtual will be a single doc or `null`.
587 */
588 justOne?: boolean;
589
590 /** If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. */
591 getters?: boolean;
592
593 /**
594 * If you set this to `true`, `populate()` will set this virtual to the number of populated
595 * documents, as opposed to the documents themselves, using `Query#countDocuments()`.
596 */
597 count?: boolean;
598
599 /** Add an extra match condition to `populate()`. */
600 match?: FilterQuery<any> | ((doc: Record<string, any>, virtual?: this) => Record<string, any> | null);
601
602 /** Add a default `limit` to the `populate()` query. */
603 limit?: number;
604
605 /** Add a default `skip` to the `populate()` query. */
606 skip?: number;
607
608 /**
609 * For legacy reasons, `limit` with `populate()` may give incorrect results because it only
610 * executes a single query for every document being populated. If you set `perDocumentLimit`,
611 * Mongoose will ensure correct `limit` per document by executing a separate query for each
612 * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })`
613 * will execute 2 additional queries if `.find()` returns 2 documents.
614 */
615 perDocumentLimit?: number;
616
617 /** Additional options like `limit` and `lean`. */
618 options?: QueryOptions<DocType> & { match?: AnyObject };
619
620 /** Additional options for plugins */
621 [extra: string]: any;
622 }
623
624 export class VirtualType<HydratedDocType> {
625 /** Applies getters to `value`. */
626 applyGetters(value: any, doc: Document): any;
627
628 /** Applies setters to `value`. */
629 applySetters(value: any, doc: Document): any;
630
631 /** Adds a custom getter to this virtual. */
632 get<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => any): this;
633
634 /** Adds a custom setter to this virtual. */
635 set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
636 }
637
638 export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
639
640 export type ProjectionElementType = number | string;
641 export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
642
643 export type SortValues = SortOrder;
644
645 export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
646
647 type _UpdateQuery<TSchema, AdditionalProperties = AnyObject> = {
648 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-field/ */
649 $currentDate?: AnyKeys<TSchema> & AdditionalProperties;
650 $inc?: AnyKeys<TSchema> & AdditionalProperties;
651 $min?: AnyKeys<TSchema> & AdditionalProperties;
652 $max?: AnyKeys<TSchema> & AdditionalProperties;
653 $mul?: AnyKeys<TSchema> & AdditionalProperties;
654 $rename?: Record<string, string>;
655 $set?: AnyKeys<TSchema> & AdditionalProperties;
656 $setOnInsert?: AnyKeys<TSchema> & AdditionalProperties;
657 $unset?: AnyKeys<TSchema> & AdditionalProperties;
658
659 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-array/ */
660 $addToSet?: AnyKeys<TSchema> & AdditionalProperties;
661 $pop?: AnyKeys<TSchema> & AdditionalProperties;
662 $pull?: AnyKeys<TSchema> & AdditionalProperties;
663 $push?: AnyKeys<TSchema> & AdditionalProperties;
664 $pullAll?: AnyKeys<TSchema> & AdditionalProperties;
665
666 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-bitwise/ */
667 $bit?: AnyKeys<TSchema>;
668 };
669
670 export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
671 export type UpdateAggregationStage = { $addFields: any } |
672 { $set: any } |
673 { $project: any } |
674 { $unset: any } |
675 { $replaceRoot: any } |
676 { $replaceWith: any };
677
678 /**
679 * Update query command to perform on the document
680 * @example
681 * ```js
682 * { age: 30 }
683 * ```
684 */
685 export type UpdateQuery<T> = AnyKeys<T> & _UpdateQuery<T> & AnyObject;
686
687 /**
688 * A more strict form of UpdateQuery that enforces updating only
689 * known top-level properties.
690 * @example
691 * ```ts
692 * function updateUser(_id: mongoose.Types.ObjectId, update: UpdateQueryKnownOnly<IUser>) {
693 * return User.updateOne({ _id }, update);
694 * }
695 * ```
696 */
697 export type UpdateQueryKnownOnly<T> = _UpdateQuery<T, {}>;
698
699 export type FlattenMaps<T> = {
700 [K in keyof T]: FlattenProperty<T[K]>;
701 };
702
703 /**
704 * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it
705 * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
706 */
707 type FlattenProperty<T> = T extends Map<any, infer V>
708 ? Record<string, V> : T extends TreatAsPrimitives
709 ? T : T extends Types.DocumentArray<infer ItemType>
710 ? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T>;
711
712 export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
713 export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function;
714
715 export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
716
717 /**
718 * Helper to choose the best option between two type helpers
719 */
720 export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
721
722 /* for ts-mongoose */
723 export class mquery { }
724
725 export default mongoose;
726}
727
\No newline at end of file