UNPKG

20.8 kBTypeScriptView Raw
1declare module 'mongoose' {
2
3 /** The Mongoose Date [SchemaType](/docs/schematypes.html). */
4 type Date = Schema.Types.Date;
5
6 /**
7 * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
8 * declaring paths in your schema that should be
9 * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
10 * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
11 * instead.
12 */
13 type Decimal128 = Schema.Types.Decimal128;
14
15 /**
16 * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
17 * declaring paths in your schema that Mongoose's change tracking, casting,
18 * and validation should ignore.
19 */
20 type Mixed = Schema.Types.Mixed;
21
22 /**
23 * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
24 * declaring paths in your schema that Mongoose should cast to numbers.
25 */
26 type Number = Schema.Types.Number;
27
28 /**
29 * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
30 * declaring paths in your schema that should be
31 * [MongoDB ObjectIds](https://www.mongodb.com/docs/manual/reference/method/ObjectId/).
32 * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
33 * instead.
34 */
35 type ObjectId = Schema.Types.ObjectId;
36
37 /** The various Mongoose SchemaTypes. */
38 const SchemaTypes: typeof Schema.Types;
39
40 type DefaultType<T> = T extends Schema.Types.Mixed ? any : Partial<ExtractMongooseArray<T>>;
41
42 class SchemaTypeOptions<T, EnforcedDocType = any> {
43 type?:
44 T extends string ? StringSchemaDefinition :
45 T extends number ? NumberSchemaDefinition :
46 T extends boolean ? BooleanSchemaDefinition :
47 T extends NativeDate ? DateSchemaDefinition :
48 T extends Map<any, any> ? SchemaDefinition<typeof Map> :
49 T extends Buffer ? SchemaDefinition<typeof Buffer> :
50 T extends Types.ObjectId ? ObjectIdSchemaDefinition :
51 T extends Types.ObjectId[] ? AnyArray<ObjectIdSchemaDefinition> | AnyArray<SchemaTypeOptions<ObjectId, EnforcedDocType>> :
52 T extends object[] ? (AnyArray<Schema<any, any, any>> | AnyArray<SchemaDefinition<Unpacked<T>>> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType>>) :
53 T extends string[] ? AnyArray<StringSchemaDefinition> | AnyArray<SchemaTypeOptions<string, EnforcedDocType>> :
54 T extends number[] ? AnyArray<NumberSchemaDefinition> | AnyArray<SchemaTypeOptions<number, EnforcedDocType>> :
55 T extends boolean[] ? AnyArray<BooleanSchemaDefinition> | AnyArray<SchemaTypeOptions<boolean, EnforcedDocType>> :
56 T extends Function[] ? AnyArray<Function | string> | AnyArray<SchemaTypeOptions<Unpacked<T>, EnforcedDocType>> :
57 T | typeof SchemaType | Schema<any, any, any> | SchemaDefinition<T> | Function | AnyArray<Function>;
58
59 /** Defines a virtual with the given name that gets/sets this path. */
60 alias?: string | string[];
61
62 /** Function or object describing how to validate this schematype. See [validation docs](https://mongoosejs.com/docs/validation.html). */
63 validate?: SchemaValidator<T, EnforcedDocType> | AnyArray<SchemaValidator<T, EnforcedDocType>>;
64
65 /** Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose's default cast error message. */
66 cast?: string |
67 boolean |
68 ((value: any) => T) |
69 [(value: any) => T, string] |
70 [((value: any) => T) | null, (value: any, path: string, model: Model<any>, kind: string) => string];
71
72 /**
73 * If true, attach a required validator to this path, which ensures this path
74 * path cannot be set to a nullish value. If a function, Mongoose calls the
75 * function and only checks for nullish values if the function returns a truthy value.
76 */
77 required?: boolean | ((this: EnforcedDocType) => boolean) | [boolean, string] | [(this: EnforcedDocType) => boolean, string];
78
79 /**
80 * The default value for this path. If a function, Mongoose executes the function
81 * and uses the return value as the default.
82 */
83 default?: DefaultType<T> | ((this: EnforcedDocType, doc: any) => DefaultType<T>) | null;
84
85 /**
86 * The model that `populate()` should use if populating this path.
87 */
88 ref?: string | Model<any> | ((this: any, doc: any) => string | Model<any>);
89
90 /**
91 * The path in the document that `populate()` should use to find the model
92 * to use.
93 */
94
95 refPath?: string | ((this: any, doc: any) => string);
96
97 /**
98 * Whether to include or exclude this path by default when loading documents
99 * using `find()`, `findOne()`, etc.
100 */
101 select?: boolean | number;
102
103 /**
104 * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
105 * build an index on this path when the model is compiled.
106 */
107 index?: boolean | IndexDirection | IndexOptions;
108
109 /**
110 * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
111 * will build a unique index on this path when the
112 * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator).
113 */
114 unique?: boolean | number;
115
116 /**
117 * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
118 * disallow changes to this path once the document is saved to the database for the first time. Read more
119 * about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html).
120 */
121 immutable?: boolean | ((this: any, doc: any) => boolean);
122
123 /**
124 * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will
125 * build a sparse index on this path.
126 */
127 sparse?: boolean | number;
128
129 /**
130 * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose
131 * will build a text index on this path.
132 */
133 text?: boolean | number | any;
134
135 /**
136 * Define a transform function for this individual schema type.
137 * Only called when calling `toJSON()` or `toObject()`.
138 */
139 transform?: (this: any, val: T) => any;
140
141 /** defines a custom getter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
142 get?: (value: any, doc?: this) => T | undefined;
143
144 /** defines a custom setter for this property using [`Object.defineProperty()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). */
145 set?: (value: any, priorVal?: T, doc?: this) => any;
146
147 /** array of allowed values for this path. Allowed for strings, numbers, and arrays of strings */
148 enum?: Array<string | number | null> | ReadonlyArray<string | number | null> | { values: Array<string | number | null> | ReadonlyArray<string | number | null>, message?: string } | { [path: string]: string | number | null };
149
150 /** The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths */
151 subtype?: number;
152
153 /** The minimum value allowed for this path. Only allowed for numbers and dates. */
154 min?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string];
155
156 /** The maximum value allowed for this path. Only allowed for numbers and dates. */
157 max?: number | NativeDate | [number, string] | [NativeDate, string] | readonly [number, string] | readonly [NativeDate, string];
158
159 /** Defines a TTL index on this path. Only allowed for dates. */
160 expires?: string | number;
161
162 /** If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. */
163 excludeIndexes?: boolean;
164
165 /** If set, overrides the child schema's `_id` option. Only allowed for subdocuments and subdocument arrays. */
166 _id?: boolean;
167
168 /** If set, specifies the type of this map's values. Mongoose will cast this map's values to the given type. */
169 of?: Function | SchemaDefinitionProperty<any>;
170
171 /** If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds */
172 auto?: boolean;
173
174 /** Attaches a validator that succeeds if the data string matches the given regular expression, and fails otherwise. */
175 match?: RegExp | [RegExp, string] | readonly [RegExp, string];
176
177 /** If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript's built-in `String#toLowerCase()`. */
178 lowercase?: boolean;
179
180 /** If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript's built-in `String#trim()`. */
181 trim?: boolean;
182
183 /** If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript's built-in `String#toUpperCase()`. */
184 uppercase?: boolean;
185
186 /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at least the given number. */
187 minlength?: number | [number, string] | readonly [number, string];
188
189 /** If set, Mongoose will add a custom validator that ensures the given string's `length` is at most the given number. */
190 maxlength?: number | [number, string] | readonly [number, string];
191
192 [other: string]: any;
193 }
194
195 interface Validator<DocType = any> {
196 message?: string | ((props: ValidatorProps) => string);
197 type?: string;
198 validator?: ValidatorFunction<DocType>;
199 reason?: Error;
200 }
201
202 type ValidatorFunction<DocType = any> = (this: DocType, value: any, validatorProperties?: Validator) => any;
203
204 class SchemaType<T = any, DocType = any> {
205 /** SchemaType constructor */
206 constructor(path: string, options?: AnyObject, instance?: string);
207
208 /** Get/set the function used to cast arbitrary values to this type. */
209 static cast(caster?: Function | boolean): Function;
210
211 static checkRequired(checkRequired?: (v: any) => boolean): (v: any) => boolean;
212
213 /** Sets a default option for this schema type. */
214 static set(option: string, value: any): void;
215
216 /** Attaches a getter for all instances of this schema type. */
217 static get(getter: (value: any) => any): void;
218
219 /** The class that Mongoose uses internally to instantiate this SchemaType's `options` property. */
220 OptionsConstructor: SchemaTypeOptions<T>;
221
222 /** Cast `val` to this schema type. Each class that inherits from schema type should implement this function. */
223 cast(val: any, doc: Document<any>, init: boolean, prev?: any, options?: any): any;
224
225 /** Sets a default value for this SchemaType. */
226 default(val: any): any;
227
228 /** Adds a getter to this schematype. */
229 get(fn: Function): this;
230
231 /**
232 * Defines this path as immutable. Mongoose prevents you from changing
233 * immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#document_Document-isNew).
234 */
235 immutable(bool: boolean): this;
236
237 /** Declares the index options for this schematype. */
238 index(options: any): this;
239
240 /** String representation of what type this is, like 'ObjectID' or 'Number' */
241 instance: string;
242
243 /** True if this SchemaType has a required validator. False otherwise. */
244 isRequired?: boolean;
245
246 /** The options this SchemaType was instantiated with */
247 options: AnyObject;
248
249 /** The path to this SchemaType in a Schema. */
250 path: string;
251
252 /**
253 * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
254 * looks at to determine the foreign collection it should query.
255 */
256 ref(ref: string | boolean | Model<any>): this;
257
258 /**
259 * Adds a required validator to this SchemaType. The validator gets added
260 * to the front of this SchemaType's validators array using unshift().
261 */
262 required(required: boolean, message?: string): this;
263
264 /** The schema this SchemaType instance is part of */
265 schema: Schema<any>;
266
267 /** Sets default select() behavior for this path. */
268 select(val: boolean): this;
269
270 /** Adds a setter to this schematype. */
271 set(fn: Function): this;
272
273 /** Declares a sparse index. */
274 sparse(bool: boolean): this;
275
276 /** Declares a full text index. */
277 text(bool: boolean): this;
278
279 /** Defines a custom function for transforming this path when converting a document to JSON. */
280 transform(fn: (value: any) => any): this;
281
282 /** Declares an unique index. */
283 unique(bool: boolean): this;
284
285 /** The validators that Mongoose should run to validate properties at this SchemaType's path. */
286 validators: Validator[];
287
288 /** Adds validator(s) for this document path. */
289 validate(obj: RegExp | ValidatorFunction<DocType> | Validator<DocType>, errorMsg?: string, type?: string): this;
290
291 /** Adds multiple validators for this document path. */
292 validateAll(validators: Array<RegExp | ValidatorFunction<DocType> | Validator<DocType>>): this;
293
294 /** Default options for this SchemaType */
295 defaultOptions?: Record<string, any>;
296 }
297
298 namespace Schema {
299 namespace Types {
300 class Array extends SchemaType implements AcceptsDiscriminator {
301 /** This schema type's name, to defend against minifiers that mangle function names. */
302 static schemaName: 'Array';
303
304 static options: { castNonArrays: boolean; };
305
306 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
307 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
308
309 /** The schematype embedded in this array */
310 caster?: SchemaType;
311
312 /** Default options for this SchemaType */
313 defaultOptions: Record<string, any>;
314
315 /**
316 * Adds an enum validator if this is an array of strings or numbers. Equivalent to
317 * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()`
318 */
319 enum(vals: string[] | number[]): this;
320 }
321
322 class BigInt extends SchemaType {
323 /** This schema type's name, to defend against minifiers that mangle function names. */
324 static schemaName: 'BigInt';
325
326 /** Default options for this SchemaType */
327 defaultOptions: Record<string, any>;
328 }
329
330 class Boolean extends SchemaType {
331 /** This schema type's name, to defend against minifiers that mangle function names. */
332 static schemaName: 'Boolean';
333
334 /** Configure which values get casted to `true`. */
335 static convertToTrue: Set<any>;
336
337 /** Configure which values get casted to `false`. */
338 static convertToFalse: Set<any>;
339
340 /** Default options for this SchemaType */
341 defaultOptions: Record<string, any>;
342 }
343
344 class Buffer extends SchemaType {
345 /** This schema type's name, to defend against minifiers that mangle function names. */
346 static schemaName: 'Buffer';
347
348 /**
349 * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/)
350 * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html).
351 */
352 subtype(subtype: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 128): this;
353
354 /** Default options for this SchemaType */
355 defaultOptions: Record<string, any>;
356 }
357
358 class Date extends SchemaType {
359 /** This schema type's name, to defend against minifiers that mangle function names. */
360 static schemaName: 'Date';
361
362 /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */
363 expires(when: number | string): this;
364
365 /** Sets a maximum date validator. */
366 max(value: NativeDate, message: string): this;
367
368 /** Sets a minimum date validator. */
369 min(value: NativeDate, message: string): this;
370
371 /** Default options for this SchemaType */
372 defaultOptions: Record<string, any>;
373 }
374
375 class Decimal128 extends SchemaType {
376 /** This schema type's name, to defend against minifiers that mangle function names. */
377 static schemaName: 'Decimal128';
378
379 /** Default options for this SchemaType */
380 defaultOptions: Record<string, any>;
381 }
382
383 class DocumentArray extends SchemaType implements AcceptsDiscriminator {
384 /** This schema type's name, to defend against minifiers that mangle function names. */
385 static schemaName: 'DocumentArray';
386
387 static options: { castNonArrays: boolean; };
388
389 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
390 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
391
392 /** The schema used for documents in this array */
393 schema: Schema;
394
395 /** The constructor used for subdocuments in this array */
396 caster?: typeof Types.Subdocument;
397
398 /** Default options for this SchemaType */
399 defaultOptions: Record<string, any>;
400 }
401
402 class Map extends SchemaType {
403 /** This schema type's name, to defend against minifiers that mangle function names. */
404 static schemaName: 'Map';
405
406 /** Default options for this SchemaType */
407 defaultOptions: Record<string, any>;
408 }
409
410 class Mixed extends SchemaType {
411 /** This schema type's name, to defend against minifiers that mangle function names. */
412 static schemaName: 'Mixed';
413
414 /** Default options for this SchemaType */
415 defaultOptions: Record<string, any>;
416 }
417
418 class Number extends SchemaType {
419 /** This schema type's name, to defend against minifiers that mangle function names. */
420 static schemaName: 'Number';
421
422 /** Sets a enum validator */
423 enum(vals: number[]): this;
424
425 /** Sets a maximum number validator. */
426 max(value: number, message: string): this;
427
428 /** Sets a minimum number validator. */
429 min(value: number, message: string): this;
430
431 /** Default options for this SchemaType */
432 defaultOptions: Record<string, any>;
433 }
434
435 class ObjectId extends SchemaType {
436 /** This schema type's name, to defend against minifiers that mangle function names. */
437 static schemaName: 'ObjectId';
438
439 /** Adds an auto-generated ObjectId default if turnOn is true. */
440 auto(turnOn: boolean): this;
441
442 /** Default options for this SchemaType */
443 defaultOptions: Record<string, any>;
444 }
445
446 class Subdocument extends SchemaType implements AcceptsDiscriminator {
447 /** This schema type's name, to defend against minifiers that mangle function names. */
448 static schemaName: string;
449
450 /** The document's schema */
451 schema: Schema;
452
453 /** Default options for this SchemaType */
454 defaultOptions: Record<string, any>;
455
456 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
457 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
458 }
459
460 class String extends SchemaType {
461 /** This schema type's name, to defend against minifiers that mangle function names. */
462 static schemaName: 'String';
463
464 /** Adds an enum validator */
465 enum(vals: string[] | any): this;
466
467 /** Adds a lowercase [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
468 lowercase(shouldApply?: boolean): this;
469
470 /** Sets a regexp validator. */
471 match(value: RegExp, message: string): this;
472
473 /** Sets a maximum length validator. */
474 maxlength(value: number, message: string): this;
475
476 /** Sets a minimum length validator. */
477 minlength(value: number, message: string): this;
478
479 /** Adds a trim [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
480 trim(shouldTrim?: boolean): this;
481
482 /** Adds an uppercase [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
483 uppercase(shouldApply?: boolean): this;
484
485 /** Default options for this SchemaType */
486 defaultOptions: Record<string, any>;
487 }
488
489 class UUID extends SchemaType {
490 /** This schema type's name, to defend against minifiers that mangle function names. */
491 static schemaName: 'UUID';
492
493 /** Default options for this SchemaType */
494 defaultOptions: Record<string, any>;
495 }
496 }
497 }
498}
499
\No newline at end of file