UNPKG

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