UNPKG

34.8 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<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<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, 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 * Returns a list of indexes that this schema declares, via `schema.index()`
279 * or by `index: true` in a path's options.
280 */
281 indexes(): Array<[IndexDefinition, IndexOptions]>;
282
283 /** Gets a schema option. */
284 get<K extends keyof SchemaOptions>(key: K): SchemaOptions[K];
285
286 /**
287 * 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),
288 * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
289 * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals),
290 * [statics](http://mongoosejs.com/docs/guide.html#statics), and
291 * [methods](http://mongoosejs.com/docs/guide.html#methods).
292 */
293 loadClass(model: Function, onlyVirtuals?: boolean): this;
294
295 /** Adds an instance method to documents constructed from Models compiled from this schema. */
296 method<Context = THydratedDocumentType>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
297 method(obj: Partial<TInstanceMethods>): this;
298
299 /** Object of currently defined methods on this schema. */
300 methods: { [F in keyof TInstanceMethods]: TInstanceMethods[F] } & AnyObject;
301
302 /** The original object passed to the schema constructor */
303 obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>, EnforcedDocType>;
304
305 /** Gets/sets schema paths. */
306 path<ResultType extends SchemaType = SchemaType<any, THydratedDocumentType>>(path: string): ResultType;
307 path<pathGeneric extends keyof EnforcedDocType>(path: pathGeneric): SchemaType<EnforcedDocType[pathGeneric]>;
308 path(path: string, constructor: any): this;
309
310 /** Lists all paths and their type in the schema. */
311 paths: {
312 [key: string]: SchemaType;
313 };
314
315 /** Returns the pathType of `path` for this schema. */
316 pathType(path: string): string;
317
318 /** Registers a plugin for this schema. */
319 plugin<PFunc extends PluginFunction<DocType, TModelType, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
320
321 /** Defines a post hook for the model. */
322
323 // PostMiddlewareFunction
324 // with errorHandler set to true
325 post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
326 post<T = THydratedDocumentType>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
327 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T, Array<any>>): this;
328 post<T = TModelType>(method: 'insertMany' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
329
330 // this = never since it never happens
331 post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: PostMiddlewareFunction<never, never>): this;
332 post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
333 post<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, T>): this;
334 // this = Document
335 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PostMiddlewareFunction<T, T>): this;
336 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
337 post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: PostMiddlewareFunction<T, T>): this;
338 // this = Query
339 post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
340 post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
341 post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
342 // this = Union of Document and Query, could be called with any of them
343 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
344 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
345
346 // ErrorHandlingMiddlewareFunction
347 // this = never since it never happens
348 post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
349 post<T = never>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & { document: false, query: boolean }, fn: ErrorHandlingMiddlewareFunction<T>): this;
350 post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
351 // this = Document
352 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
353 post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
354 post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
355 // this = Query
356 post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
357 post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
358 post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
359 // this = Union of Document and Query, could be called with any of them
360 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
361 post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
362
363 // method aggregate and insertMany with PostMiddlewareFunction
364 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
365 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
366 post<T = TModelType>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T, T>): this;
367 post<T = TModelType>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
368
369 // method aggregate and insertMany with ErrorHandlingMiddlewareFunction
370 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
371 post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
372 post<T = TModelType>(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
373 post<T = TModelType>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
374
375 /** Defines a pre hook for the model. */
376 // this = never since it never happens
377 pre<T = never>(method: 'save', options: SchemaPreOptions & { document: false, query: boolean }, fn: PreSaveMiddlewareFunction<T>): this;
378 pre<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: false }, fn: PreMiddlewareFunction<T>): this;
379 pre<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions & { document: boolean, query: false }, fn: PreMiddlewareFunction<T>): this;
380 pre<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: boolean }, fn: PreMiddlewareFunction<T>): this;
381 // this = Union of Document and Query, could be called with any of them
382 pre<T = THydratedDocumentType | Query<any, any>>(
383 method: MongooseQueryAndDocumentMiddleware | MongooseQueryAndDocumentMiddleware[] | RegExp,
384 options: SchemaPreOptions & { document: true, query: true },
385 fn: PreMiddlewareFunction<T>
386 ): this;
387 // this = Document
388 pre<T = THydratedDocumentType>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
389 pre<T = THydratedDocumentType>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction<T>): this;
390 pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PreMiddlewareFunction<T>): this;
391 pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
392 pre<T = THydratedDocumentType>(
393 method: MongooseQueryAndDocumentMiddleware | MongooseQueryAndDocumentMiddleware[] | RegExp,
394 options: SchemaPreOptions & { document: true },
395 fn: PreMiddlewareFunction<T>
396 ): this;
397 pre<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: false }, fn: PreMiddlewareFunction<T>): this;
398 // this = Query
399 pre<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PreMiddlewareFunction<T>): this;
400 pre<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
401 pre<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: true }, fn: PreMiddlewareFunction<T>): this;
402 // this = Union of Document and Query, could be called with any of them
403 pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreMiddlewareFunction<T>): this;
404 pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
405 // method aggregate
406 pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
407 pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
408 /* method insertMany */
409 pre<T = TModelType>(
410 method: 'insertMany' | RegExp,
411 fn: (
412 this: T,
413 next: (err?: CallbackError) => void,
414 docs: any | Array<any>,
415 options?: InsertManyOptions & { lean?: boolean }
416 ) => void | Promise<void>
417 ): this;
418 pre<T = TModelType>(
419 method: 'insertMany' | RegExp,
420 options: SchemaPreOptions,
421 fn: (
422 this: T,
423 next: (err?: CallbackError) => void,
424 docs: any | Array<any>,
425 options?: InsertManyOptions & { lean?: boolean }
426 ) => void | Promise<void>
427 ): this;
428
429 /** Object of currently defined query helpers on this schema. */
430 query: TQueryHelpers;
431
432 /** Adds a method call to the queue. */
433 queue(name: string, args: any[]): this;
434
435 /** Removes the given `path` (or [`paths`]). */
436 remove(paths: string | Array<string>): this;
437
438 /** Removes index by name or index spec */
439 remove(index: string | AnyObject): this;
440
441 /** Returns an Array of path strings that are required by this schema. */
442 requiredPaths(invalidate?: boolean): string[];
443
444 /** Sets a schema option. */
445 set<K extends keyof SchemaOptions>(key: K, value: SchemaOptions[K], _tags?: any): this;
446
447 /** Adds static "class" methods to Models compiled from this schema. */
448 static<K extends keyof TStaticMethods>(name: K, fn: TStaticMethods[K]): this;
449 static(obj: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: TModelType, ...args: any[]) => any }): this;
450 static(name: string, fn: (this: TModelType, ...args: any[]) => any): this;
451
452 /** Object of currently defined statics on this schema. */
453 statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } &
454 { [name: string]: (this: TModelType, ...args: any[]) => unknown };
455
456 /** Creates a virtual type with the given name. */
457 virtual<T = HydratedDocument<DocType, TVirtuals & TInstanceMethods, TQueryHelpers>>(
458 name: keyof TVirtuals | string,
459 options?: VirtualTypeOptions<T, DocType>
460 ): VirtualType<T>;
461
462 /** Object of currently defined virtuals on this schema */
463 virtuals: TVirtuals;
464
465 /** Returns the virtual type with the given `name`. */
466 virtualpath<T = THydratedDocumentType>(name: string): VirtualType<T> | null;
467
468 static ObjectId: typeof Schema.Types.ObjectId;
469 }
470
471 export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
472 export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
473 export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
474 export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
475 export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
476
477 export type SchemaDefinitionWithBuiltInClass<T> = T extends number
478 ? NumberSchemaDefinition
479 : T extends string
480 ? StringSchemaDefinition
481 : T extends boolean
482 ? BooleanSchemaDefinition
483 : T extends NativeDate
484 ? DateSchemaDefinition
485 : (Function | string);
486
487 export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any> = SchemaDefinitionWithBuiltInClass<T> |
488 SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType> |
489 typeof SchemaType |
490 Schema<any, any, any> |
491 Schema<any, any, any>[] |
492 SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType>[] |
493 Function[] |
494 SchemaDefinition<T, EnforcedDocType> |
495 SchemaDefinition<Unpacked<T>, EnforcedDocType>[] |
496 typeof Schema.Types.Mixed |
497 MixedSchemaTypeOptions<EnforcedDocType>;
498
499 export type SchemaDefinition<T = undefined, EnforcedDocType = any> = T extends undefined
500 ? { [path: string]: SchemaDefinitionProperty; }
501 : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType>; };
502
503 export type AnyArray<T> = T[] | ReadonlyArray<T>;
504 export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
505
506 export interface MixedSchemaTypeOptions<EnforcedDocType> extends SchemaTypeOptions<Schema.Types.Mixed, EnforcedDocType> {
507 type: typeof Schema.Types.Mixed;
508 }
509
510 export type RefType =
511 | number
512 | string
513 | Buffer
514 | undefined
515 | Types.ObjectId
516 | Types.Buffer
517 | typeof Schema.Types.Number
518 | typeof Schema.Types.String
519 | typeof Schema.Types.Buffer
520 | typeof Schema.Types.ObjectId;
521
522
523 export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
524
525 export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
526 /** If `ref` is not nullish, this becomes a populated virtual. */
527 ref?: string | Function;
528
529 /** The local field to populate on if this is a populated virtual. */
530 localField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
531
532 /** The foreign field to populate on if this is a populated virtual. */
533 foreignField?: string | ((this: HydratedDocType, doc: HydratedDocType) => string);
534
535 /**
536 * By default, a populated virtual is an array. If you set `justOne`,
537 * the populated virtual will be a single doc or `null`.
538 */
539 justOne?: boolean;
540
541 /** If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. */
542 getters?: boolean;
543
544 /**
545 * If you set this to `true`, `populate()` will set this virtual to the number of populated
546 * documents, as opposed to the documents themselves, using `Query#countDocuments()`.
547 */
548 count?: boolean;
549
550 /** Add an extra match condition to `populate()`. */
551 match?: FilterQuery<any> | ((doc: Record<string, any>, virtual?: this) => Record<string, any> | null);
552
553 /** Add a default `limit` to the `populate()` query. */
554 limit?: number;
555
556 /** Add a default `skip` to the `populate()` query. */
557 skip?: number;
558
559 /**
560 * For legacy reasons, `limit` with `populate()` may give incorrect results because it only
561 * executes a single query for every document being populated. If you set `perDocumentLimit`,
562 * Mongoose will ensure correct `limit` per document by executing a separate query for each
563 * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })`
564 * will execute 2 additional queries if `.find()` returns 2 documents.
565 */
566 perDocumentLimit?: number;
567
568 /** Additional options like `limit` and `lean`. */
569 options?: QueryOptions<DocType> & { match?: AnyObject };
570
571 /** Additional options for plugins */
572 [extra: string]: any;
573 }
574
575 export class VirtualType<HydratedDocType> {
576 /** Applies getters to `value`. */
577 applyGetters(value: any, doc: Document): any;
578
579 /** Applies setters to `value`. */
580 applySetters(value: any, doc: Document): any;
581
582 /** Adds a custom getter to this virtual. */
583 get<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => any): this;
584
585 /** Adds a custom setter to this virtual. */
586 set<T = HydratedDocType>(fn: (this: T, value: any, virtualType: VirtualType<T>, doc: T) => void): this;
587 }
588
589 export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
590
591 export type ProjectionElementType = number | string;
592 export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
593
594 export type SortValues = SortOrder;
595
596 export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
597
598 type _UpdateQuery<TSchema, AdditionalProperties = AnyObject> = {
599 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-field/ */
600 $currentDate?: AnyKeys<TSchema> & AdditionalProperties;
601 $inc?: AnyKeys<TSchema> & AdditionalProperties;
602 $min?: AnyKeys<TSchema> & AdditionalProperties;
603 $max?: AnyKeys<TSchema> & AdditionalProperties;
604 $mul?: AnyKeys<TSchema> & AdditionalProperties;
605 $rename?: Record<string, string>;
606 $set?: AnyKeys<TSchema> & AdditionalProperties;
607 $setOnInsert?: AnyKeys<TSchema> & AdditionalProperties;
608 $unset?: AnyKeys<TSchema> & AdditionalProperties;
609
610 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-array/ */
611 $addToSet?: AnyKeys<TSchema> & AdditionalProperties;
612 $pop?: AnyKeys<TSchema> & AdditionalProperties;
613 $pull?: AnyKeys<TSchema> & AdditionalProperties;
614 $push?: AnyKeys<TSchema> & AdditionalProperties;
615 $pullAll?: AnyKeys<TSchema> & AdditionalProperties;
616
617 /** @see https://www.mongodb.com/docs/manual/reference/operator/update-bitwise/ */
618 $bit?: AnyKeys<TSchema>;
619 };
620
621 export type UpdateWithAggregationPipeline = UpdateAggregationStage[];
622 export type UpdateAggregationStage = { $addFields: any } |
623 { $set: any } |
624 { $project: any } |
625 { $unset: any } |
626 { $replaceRoot: any } |
627 { $replaceWith: any };
628
629 /**
630 * Update query command to perform on the document
631 * @example
632 * ```js
633 * { age: 30 }
634 * ```
635 */
636 export type UpdateQuery<T> = _UpdateQuery<T> & AnyObject;
637
638 /**
639 * A more strict form of UpdateQuery that enforces updating only
640 * known top-level properties.
641 * @example
642 * ```ts
643 * function updateUser(_id: mongoose.Types.ObjectId, update: UpdateQueryKnownOnly<IUser>) {
644 * return User.updateOne({ _id }, update);
645 * }
646 * ```
647 */
648 export type UpdateQueryKnownOnly<T> = _UpdateQuery<T, {}>;
649
650 export type FlattenMaps<T> = {
651 [K in keyof T]: FlattenProperty<T[K]>;
652 };
653
654 /**
655 * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it
656 * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
657 */
658 type FlattenProperty<T> = T extends Map<any, infer V>
659 ? Record<string, V> : T extends TreatAsPrimitives
660 ? T : T extends Types.DocumentArray<infer ItemType>
661 ? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T>;
662
663 export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
664 export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function;
665
666 export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
667
668 /**
669 * Helper to choose the best option between two type helpers
670 */
671 export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
672
673 /* for ts-mongoose */
674 export class mquery { }
675
676 export default mongoose;
677}
678
\No newline at end of file