UNPKG

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