UNPKG

20.8 kBTypeScriptView Raw
1import type * as mongoose from 'mongoose';
2import type { Severity, PropType } from './internal/constants';
3/**
4 * Get the Type of an instance of a Document with Class properties
5 * @example
6 * ```ts
7 * class ClassName {}
8 * const NameModel = getModelForClass(ClassName);
9 *
10 * const doc: DocumentType<ClassName> = await NameModel.create({});
11 * ```
12 */
13export declare type DocumentType<T, QueryHelpers = BeAnObject> = (T extends {
14 _id: unknown;
15} ? mongoose.Document<T['_id'], QueryHelpers> & T : mongoose.Document<any, QueryHelpers> & T) & IObjectWithTypegooseFunction;
16/**
17 * Used Internally for ModelTypes
18 */
19export declare type ModelType<T, QueryHelpers = BeAnObject> = mongoose.Model<DocumentType<T, QueryHelpers>, QueryHelpers>;
20/**
21 * Any-param Constructor
22 */
23export declare type AnyParamConstructor<T> = new (...args: any) => T;
24/**
25 * The Type of a Model that gets returned by "getModelForClass" and "setModelForClass"
26 */
27export declare type ReturnModelType<U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject> = ModelType<InstanceType<U>, QueryHelpers> & U;
28/** Generic "Function" type, because typescript does not like using "Function" directly in strict mode */
29export declare type Func = (...args: any[]) => any;
30/**
31 * The Type of a function to generate a custom model name.
32 */
33export declare type CustomNameFunction = (options: IModelOptions) => string;
34/**
35 * Defer an reference with an function (or as other projects call it "Forward declaration")
36 * @param type This is just to comply with the common pattern of `type => ActualType`
37 */
38export declare type DeferredFunc<T = any> = (...args: unknown[]) => T;
39/**
40 * Dynamic Functions, since mongoose 4.13
41 * @param doc The Document current document
42 */
43export declare type DynamicStringFunc<T extends AnyParamConstructor<any>> = (doc: DocumentType<T>) => string;
44/**
45 * This Interface for most properties uses "mongoose.SchemaTypeOptions<any>['']", but for some special (or typegoose custom) options, it is not used
46 *
47 * Example: `index` is directly from mongoose, where as `type` is from typegoose
48 */
49export interface BasePropOptions {
50 /**
51 * include this value?
52 * @default true (Implicitly)
53 */
54 select?: mongoose.SchemaTypeOptions<any>['select'];
55 /**
56 * is this value required?
57 * @default false (Implicitly)
58 */
59 required?: mongoose.SchemaTypeOptions<any>['required'];
60 /** Only accept Values from the Enum(|Array) */
61 enum?: string[] | BeAnObject;
62 /**
63 * Add "null" to the enum array
64 * Note: Custom Typegoose Option
65 */
66 addNullToEnum?: boolean;
67 /** Give the Property a default Value */
68 default?: mongoose.SchemaTypeOptions<any>['default'];
69 /** Give an Validator RegExp or Function */
70 validate?: mongoose.SchemaTypeOptions<any>['validate'];
71 /**
72 * Should this property have an "unique" index?
73 * @link https://docs.mongodb.com/manual/indexes/#unique-indexes
74 */
75 unique?: mongoose.SchemaTypeOptions<any>['unique'];
76 /**
77 * Should this property have an index?
78 * Note: dont use this if you want to do an compound index
79 * @link https://docs.mongodb.com/manual/indexes
80 */
81 index?: mongoose.SchemaTypeOptions<any>['index'];
82 /**
83 * Should this property have an "sparse" index?
84 * @link https://docs.mongodb.com/manual/indexes/#sparse-indexes
85 */
86 sparse?: mongoose.SchemaTypeOptions<any>['sparse'];
87 /**
88 * Should this property have an "expires" index?
89 * @link https://docs.mongodb.com/manual/tutorial/expire-data
90 */
91 expires?: mongoose.SchemaTypeOptions<any>['expires'];
92 /**
93 * Should this property have an "text" index?
94 * @link https://mongoosejs.com/docs/api.html#schematype_SchemaType-text
95 */
96 text?: mongoose.SchemaTypeOptions<any>['text'];
97 /** Should subdocuments get their own id?
98 * @default true (Implicitly)
99 */
100 _id?: mongoose.SchemaTypeOptions<any>['_id'];
101 /**
102 * Set a Setter (Non-Virtual) to pre-process your value
103 * (when using get/set both are required)
104 * Please note that the option `type` is required, if get/set saves a different value than what is defined
105 * @param value The Value that needs to get modified
106 * @returns The Value, but modified OR anything
107 * @example
108 * ```ts
109 * function setHello(val: string): string {
110 * return val.toLowerCase()
111 * }
112 * function getHello(val: string): string {
113 * return val.toUpperCase();
114 * }
115 * class Dummy {
116 * @prop({ set: setHello, get: getHello }) // many options can be used, like required
117 * public hello: string;
118 * }
119 * ```
120 */
121 set?: mongoose.SchemaTypeOptions<any>['set'];
122 /**
123 * Set a Getter (Non-Virtual) to Post-process your value
124 * (when using get/set both are required)
125 * Please note that the option `type` is required, if get/set saves a different value than what is defined
126 * @param value The Value that needs to get modified
127 * @returns The Value, but modified OR anything
128 * @example
129 * ```ts
130 * function setHello(val: string): string {
131 * return val.toLowerCase()
132 * }
133 * function getHello(val: string): string {
134 * return val.toUpperCase();
135 * }
136 * class Dummy {
137 * @prop({ set: setHello, get: getHello }) // many options can be used, like required
138 * public hello: string;
139 * }
140 * ```
141 */
142 get?: mongoose.SchemaTypeOptions<any>['get'];
143 /**
144 * This may be needed if get/set is used
145 * (this sets the type how it is saved to the DB)
146 */
147 type?: DeferredFunc<AnyParamConstructor<any>> | DeferredFunc<unknown> | unknown;
148 /**
149 * Make a property read-only
150 * @example
151 * ```ts
152 * class SomeClass {
153 * @prop({ immutable: true })
154 * public someprop: Readonly<string>;
155 * }
156 * ```
157 */
158 immutable?: mongoose.SchemaTypeOptions<any>['immutable'];
159 /**
160 * Give the Property an alias in the output
161 *
162 * Note: you should include the alias as a variable in the class, but not with a prop decorator
163 * @example
164 * ```ts
165 * class Dummy {
166 * @prop({ alias: "helloWorld" })
167 * public hello: string; // normal, with @prop
168 * public helloWorld: string; // is just for type Completion, will not be included in the DB
169 * }
170 * ```
171 */
172 alias?: mongoose.SchemaTypeOptions<any>['alias'];
173 /**
174 * This option as only an effect when the plugin `mongoose-autopopulate` is used
175 */
176 autopopulate?: boolean | Function | KeyStringAny;
177 /** Reference an other Document (you should use Ref<T> as Prop type) */
178 ref?: DeferredFunc<string | AnyParamConstructor<any> | DynamicStringFunc<any>> | string | AnyParamConstructor<any>;
179 /** Take the Path and try to resolve it to a Model */
180 refPath?: string;
181 /**
182 * Set the Nested Discriminators
183 *
184 * Note: "_id: false" as an prop option dosnt work here
185 *
186 * Note: Custom Typegoose Option
187 */
188 discriminators?: DeferredFunc<(AnyParamConstructor<any> | DiscriminatorObject)[]>;
189 /**
190 * Use option {@link BasePropOptions.type}
191 * @see https://typegoose.github.io/typegoose/docs/api/decorators/prop#map-options
192 * @see https://typegoose.github.io/typegoose/docs/api/decorators/prop#proptype
193 */
194 of?: never;
195 /**
196 * If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds
197 *
198 * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
199 */
200 auto?: mongoose.SchemaTypeOptions<any>['auto'];
201 /**
202 * The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths
203 *
204 * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
205 */
206 subtype?: mongoose.SchemaTypeOptions<any>['subtype'];
207 /**
208 * If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays.
209 *
210 * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
211 */
212 excludeIndexes?: mongoose.SchemaTypeOptions<any>['excludeIndexes'];
213 /**
214 * Define a transform function for this individual schema type.
215 * Only called when calling `toJSON()` or `toObject()`.
216 *
217 * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions
218 */
219 transform?: mongoose.SchemaTypeOptions<any>['transform'];
220 [extra: string]: any;
221}
222export interface InnerOuterOptions {
223 /**
224 * Use this to define inner-options
225 * Use this if the auto-mapping is not correct or for plugin options
226 *
227 * Please open a new issue if some option is mismatched or not existing / mapped
228 */
229 innerOptions?: KeyStringAny;
230 /**
231 * Use this to define outer-options
232 * Use this if the auto-mapping is not correct or for plugin options
233 *
234 * Please open a new issue if some option is mismatched or not existing / mapped
235 */
236 outerOptions?: KeyStringAny;
237}
238/**
239 * Internal type for `utils.mapOptions`
240 * @internal
241 */
242export interface MappedInnerOuterOptions {
243 /**
244 * Mapped options for the inner of the Type
245 */
246 inner: NonNullable<KeyStringAny>;
247 /**
248 * Mapped options for the outer of the type
249 */
250 outer: NonNullable<KeyStringAny>;
251}
252/** Options for Array's */
253export interface ArrayPropOptions extends BasePropOptions, InnerOuterOptions {
254 /**
255 * How many dimensions this Array should have
256 * (needs to be higher than 0)
257 *
258 * Note: Custom Typegoose Option
259 * @default 1
260 */
261 dim?: number;
262 /**
263 * Set if Non-Array values will be cast to an array
264 *
265 * NOTE: This option currently only really affects "DocumentArray" and not normal arrays, https://github.com/Automattic/mongoose/issues/10398
266 * @see https://mongoosejs.com/docs/api/schemaarray.html#schemaarray_SchemaArray.options
267 * @example
268 * ```ts
269 * new Model({ array: "string" });
270 * // will be cast to equal
271 * new Model({ array: ["string"] });
272 * ```
273 * @default true
274 */
275 castNonArrays?: boolean;
276}
277/** Options For Map's */
278export interface MapPropOptions extends BasePropOptions, InnerOuterOptions {
279}
280export interface ValidateNumberOptions {
281 /** Only allow numbers that are higher than this */
282 min?: mongoose.SchemaTypeOptions<any>['min'];
283 /** Only allow numbers lower than this */
284 max?: mongoose.SchemaTypeOptions<any>['max'];
285 /** Only allow Values from the enum */
286 enum?: number[];
287}
288export interface ValidateStringOptions {
289 /** Only allow values that match this RegExp */
290 match?: mongoose.SchemaTypeOptions<any>['match'];
291 /** Only allow Values from the enum */
292 enum?: string[];
293 /** Only allow values that have at least this length */
294 minlength?: mongoose.SchemaTypeOptions<any>['minlength'];
295 /** Only allow values that have at max this length */
296 maxlength?: mongoose.SchemaTypeOptions<any>['maxlength'];
297}
298export interface TransformStringOptions {
299 /** Should it be lowercased before save? */
300 lowercase?: mongoose.SchemaTypeOptions<any>['lowercase'];
301 /** Should it be uppercased before save? */
302 uppercase?: mongoose.SchemaTypeOptions<any>['uppercase'];
303 /** Should it be trimmed before save? */
304 trim?: mongoose.SchemaTypeOptions<any>['trim'];
305}
306export interface VirtualOptions {
307 /** Reference another Document (Ref<T> should be used as property type) */
308 ref: NonNullable<BasePropOptions['ref']>;
309 /** Which property(on the current-Class) to match `foreignField` against */
310 localField: mongoose.VirtualTypeOptions['localField'];
311 /** Which property(on the ref-Class) to match `localField` against */
312 foreignField: mongoose.VirtualTypeOptions['foreignField'];
313 /** Return as One Document(true) or as Array(false) */
314 justOne?: mongoose.VirtualTypeOptions['justOne'];
315 /** Return the number of Documents found instead of the actual Documents */
316 count?: mongoose.VirtualTypeOptions['count'];
317 /** Extra Query Options */
318 options?: mongoose.VirtualTypeOptions['options'];
319 /** Match Options */
320 match?: KeyStringAny | ((doc: any) => KeyStringAny);
321 /**
322 * If you set this to `true`, Mongoose will call any custom getters you defined on this virtual.
323 *
324 * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
325 */
326 getters?: mongoose.VirtualTypeOptions['getters'];
327 /**
328 * Add a default `limit` to the `populate()` query.
329 *
330 * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
331 */
332 limit?: mongoose.VirtualTypeOptions['limit'];
333 /**
334 * Add a default `skip` to the `populate()` query.
335 *
336 * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
337 */
338 skip?: mongoose.VirtualTypeOptions['skip'];
339 /**
340 * For legacy reasons, `limit` with `populate()` may give incorrect results because it only
341 * executes a single query for every document being populated. If you set `perDocumentLimit`,
342 * Mongoose will ensure correct `limit` per document by executing a separate query for each
343 * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })`
344 * will execute 2 additional queries if `.find()` returns 2 documents.
345 *
346 * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions
347 */
348 perDocumentLimit?: mongoose.VirtualTypeOptions['perDocumentLimit'];
349 [extra: string]: any;
350}
351export declare type PropOptionsForNumber = BasePropOptions & ValidateNumberOptions;
352export declare type PropOptionsForString = BasePropOptions & TransformStringOptions & ValidateStringOptions;
353export declare type RefType = mongoose.RefType;
354/**
355 * Reference another Model
356 */
357export declare type Ref<PopulatedType, RawId extends mongoose.RefType = (PopulatedType extends {
358 _id?: mongoose.RefType;
359} ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined> = mongoose.PopulatedDoc<PopulatedType, RawId>;
360/**
361 * An Function type for a function that doesn't have any arguments and doesn't return anything
362 */
363export declare type EmptyVoidFn = () => void;
364export interface DiscriminatorObject {
365 /** The Class to use */
366 type: AnyParamConstructor<any>;
367 /**
368 * The Name to differentiate between other classes
369 * Mongoose JSDOC: [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
370 * @default {string} The output of "getName"
371 */
372 value?: string;
373}
374export interface IModelOptions {
375 /** An Existing Mongoose Connection */
376 existingMongoose?: mongoose.Mongoose;
377 /** Supports all Mongoose's Schema Options */
378 schemaOptions?: mongoose.SchemaOptions;
379 /** An Existing Connection */
380 existingConnection?: mongoose.Connection;
381 /** Typegoose Custom Options */
382 options?: ICustomOptions;
383}
384/** Typegoose options, mostly for "modelOptions({ options: ICustomOptions })" */
385export interface ICustomOptions {
386 /**
387 * Set the modelName of the class.
388 * If it is a function, the function will be executed. The function will override
389 * "automaticName". If "automaticName" is true and "customName" is a string, it
390 * sets a *suffix* instead of the whole name.
391 * @default schemaOptions.collection
392 */
393 customName?: string | CustomNameFunction;
394 /**
395 * Enable Automatic Name generation of a model
396 * Example:
397 * class with name of "SomeClass"
398 * and option "collection" of "SC"
399 *
400 * will generate the name of "SomeClass_SC"
401 * @default false
402 */
403 automaticName?: boolean;
404 /** Allow "mongoose.Schema.Types.Mixed"? */
405 allowMixed?: Severity;
406 /** Run "model.syncIndexes" when model is finished compiling? */
407 runSyncIndexes?: boolean;
408}
409/** Type for the Values stored in the Reflection for Properties */
410export interface DecoratedPropertyMetadata {
411 /** Prop Options */
412 options: any;
413 /** Target Class */
414 target: AnyParamConstructor<any>;
415 /** Property name */
416 key: string | symbol;
417 /** What is it for a prop type? */
418 whatis?: PropType;
419}
420export declare type DecoratedPropertyMetadataMap = Map<string | symbol, DecoratedPropertyMetadata>;
421/**
422 * copy-paste from mongodb package (should be same as IndexOptions from 'mongodb')
423 */
424export interface IndexOptions<T> extends mongoose.IndexOptions {
425 weights?: Partial<Record<keyof T, number>>;
426}
427/**
428 * Type for the Values stored in the Reflection for Indexes
429 * @example
430 * ```ts
431 * const indices: IIndexArray[] = Reflect.getMetadata(DecoratorKeys.Index, target) || []);
432 * ```
433 */
434export interface IIndexArray<T> {
435 fields: KeyStringAny;
436 options?: IndexOptions<T>;
437}
438/**
439 * Type for the Values stored in the Reflection for Plugins
440 * @example
441 * ```ts
442 * const plugins: IPluginsArray<any>[] = Array.from(Reflect.getMetadata(DecoratorKeys.Plugins, target) ?? []);
443 * ```
444 */
445export interface IPluginsArray<T> {
446 mongoosePlugin: Func;
447 options: T;
448}
449/**
450 * Type for the Values stored in the Reflection for Virtual Populates
451 * @example
452 * ```ts
453 * const virtuals: VirtualPopulateMap = new Map(Reflect.getMetadata(DecoratorKeys.VirtualPopulate, target.constructor) ?? []);
454 * ```
455 */
456export declare type VirtualPopulateMap = Map<string, any & VirtualOptions>;
457/**
458 * Gets the signature (parameters with their types, and the return type) of a function type.
459 *
460 * @description Should be used when defining an interface for a class that uses query methods.
461 *
462 * @example
463 * ```ts
464 * function sendMessage(recipient: string, sender: string, priority: number, retryIfFails: boolean) {
465 * // some logic...
466 * return true;
467 * }
468 *
469 * // Both of the following types will be identical.
470 * type SendMessageType = AsQueryMethod<typeof sendMessage>;
471 * type SendMessageManualType = (recipient: string, sender: string, priority: number, retryIfFails: boolean) => boolean;
472 * ```
473 */
474export declare type AsQueryMethod<T extends (...args: any) => any> = (...args: Parameters<T>) => ReturnType<T>;
475/**
476 * Helper type to easily set the `this` type in a QueryHelper function
477 *
478 * @example
479 * function findById(this: QueryHelperThis<YourClass, YourClassQueryHelpers>, id: string) {
480 * return this.findOne({ _id: id });
481 * }
482 */
483export declare type QueryHelperThis<T extends AnyParamConstructor<any>, QueryHelpers, S = DocumentType<T, QueryHelpers>> = mongoose.QueryWithHelpers<S | null, S, QueryHelpers>;
484/**
485 * Type for the Values stored in the Reflection for Query Methods
486 * @example
487 * ```ts
488 * const queryMethods: QueryMethodMap = new Map(Reflect.getMetadata(DecoratorKeys.QueryMethod, target) ?? []);
489 * ```
490 */
491export declare type QueryMethodMap = Map<string, Func>;
492/**
493 * Type for the Values stored in the Reflection for Nested Discriminators
494 * @example
495 * ```ts
496 * const disMap: NestedDiscriminatorsMap = new Map(Reflect.getMetadata(DecoratorKeys.NestedDiscriminators, target) ?? []);
497 * ```
498 */
499export declare type NestedDiscriminatorsMap = Map<string, DiscriminatorObject[]>;
500/** A Helper type to combine both mongoose Hook Option types */
501export declare type HookOptionsEither = mongoose.SchemaPreOptions | mongoose.SchemaPostOptions;
502/**
503 * Type for the Values stored in the Reflection for Hooks
504 * @example
505 * ```ts
506 * const postHooks: IHooksArray[] = Array.from(Reflect.getMetadata(DecoratorKeys.HooksPost, target) ?? []);
507 * ```
508 */
509export interface IHooksArray {
510 /** The Function to add as a hooks */
511 func: Func;
512 /** The Method to where this hook gets triggered */
513 method: string | RegExp;
514 /**
515 * Options for Hooks
516 * @see https://mongoosejs.com/docs/middleware.html#naming
517 */
518 options: HookOptionsEither;
519}
520export interface IGlobalOptions {
521 /** Typegoose Options */
522 options?: ICustomOptions;
523 /** Schema Options that should get applied to all models */
524 schemaOptions?: mongoose.SchemaOptions;
525 /**
526 * Global Options for general Typegoose
527 * (There are currently none)
528 */
529 globalOptions?: BeAnObject;
530}
531/** Interface describing a Object that has a "typegooseName" Function */
532export interface IObjectWithTypegooseFunction {
533 typegooseName(): string;
534}
535/** Interface describing a Object that has a "typegooseName" Value */
536export interface IObjectWithTypegooseName {
537 typegooseName: string;
538}
539/** For the types that error that seemingly dont have a prototype */
540export interface IPrototype {
541 prototype?: any;
542}
543/** An Helper Interface for key: any: string */
544export interface KeyStringAny {
545 [key: string]: any;
546}
547/**
548 * The Return Type of "utils.getType"
549 */
550export interface GetTypeReturn {
551 type: unknown;
552 dim: number;
553}
554/**
555 * This type is for lint error "ban-types"
556 */
557export declare type BeAnObject = Record<string, any>;