UNPKG

21 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 cast<ResultType>(val: any, doc?: Document<any>, init?: boolean, prev?: any, options?: any): ResultType;
225
226 /** Sets a default value for this SchemaType. */
227 default(val: any): any;
228
229 /** Adds a getter to this schematype. */
230 get(fn: Function): this;
231
232 /**
233 * Defines this path as immutable. Mongoose prevents you from changing
234 * immutable paths unless the parent document has [`isNew: true`](/docs/api/document.html#document_Document-isNew).
235 */
236 immutable(bool: boolean): this;
237
238 /** Declares the index options for this schematype. */
239 index(options: any): this;
240
241 /** String representation of what type this is, like 'ObjectID' or 'Number' */
242 instance: string;
243
244 /** True if this SchemaType has a required validator. False otherwise. */
245 isRequired?: boolean;
246
247 /** The options this SchemaType was instantiated with */
248 options: AnyObject;
249
250 /** The path to this SchemaType in a Schema. */
251 path: string;
252
253 /**
254 * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html)
255 * looks at to determine the foreign collection it should query.
256 */
257 ref(ref: string | boolean | Model<any>): this;
258
259 /**
260 * Adds a required validator to this SchemaType. The validator gets added
261 * to the front of this SchemaType's validators array using unshift().
262 */
263 required(required: boolean, message?: string): this;
264
265 /** The schema this SchemaType instance is part of */
266 schema: Schema<any>;
267
268 /** Sets default select() behavior for this path. */
269 select(val: boolean): this;
270
271 /** Adds a setter to this schematype. */
272 set(fn: Function): this;
273
274 /** Declares a sparse index. */
275 sparse(bool: boolean): this;
276
277 /** Declares a full text index. */
278 text(bool: boolean): this;
279
280 /** Defines a custom function for transforming this path when converting a document to JSON. */
281 transform(fn: (value: any) => any): this;
282
283 /** Declares an unique index. */
284 unique(bool: boolean): this;
285
286 /** The validators that Mongoose should run to validate properties at this SchemaType's path. */
287 validators: Validator[];
288
289 /** Adds validator(s) for this document path. */
290 validate(obj: RegExp | ValidatorFunction<DocType> | Validator<DocType>, errorMsg?: string, type?: string): this;
291
292 /** Adds multiple validators for this document path. */
293 validateAll(validators: Array<RegExp | ValidatorFunction<DocType> | Validator<DocType>>): this;
294
295 /** Default options for this SchemaType */
296 defaultOptions?: Record<string, any>;
297 }
298
299 namespace Schema {
300 namespace Types {
301 class Array extends SchemaType implements AcceptsDiscriminator {
302 /** This schema type's name, to defend against minifiers that mangle function names. */
303 static schemaName: 'Array';
304
305 static options: { castNonArrays: boolean; };
306
307 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
308 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
309
310 /** The schematype embedded in this array */
311 caster?: SchemaType;
312
313 /** Default options for this SchemaType */
314 defaultOptions: Record<string, any>;
315
316 /**
317 * Adds an enum validator if this is an array of strings or numbers. Equivalent to
318 * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()`
319 */
320 enum(vals: string[] | number[]): this;
321 }
322
323 class BigInt extends SchemaType {
324 /** This schema type's name, to defend against minifiers that mangle function names. */
325 static schemaName: 'BigInt';
326
327 /** Default options for this SchemaType */
328 defaultOptions: Record<string, any>;
329 }
330
331 class Boolean extends SchemaType {
332 /** This schema type's name, to defend against minifiers that mangle function names. */
333 static schemaName: 'Boolean';
334
335 /** Configure which values get casted to `true`. */
336 static convertToTrue: Set<any>;
337
338 /** Configure which values get casted to `false`. */
339 static convertToFalse: Set<any>;
340
341 /** Default options for this SchemaType */
342 defaultOptions: Record<string, any>;
343 }
344
345 class Buffer extends SchemaType {
346 /** This schema type's name, to defend against minifiers that mangle function names. */
347 static schemaName: 'Buffer';
348
349 /**
350 * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/)
351 * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html).
352 */
353 subtype(subtype: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 128): this;
354
355 /** Default options for this SchemaType */
356 defaultOptions: Record<string, any>;
357 }
358
359 class Date extends SchemaType {
360 /** This schema type's name, to defend against minifiers that mangle function names. */
361 static schemaName: 'Date';
362
363 /** Declares a TTL index (rounded to the nearest second) for _Date_ types only. */
364 expires(when: number | string): this;
365
366 /** Sets a maximum date validator. */
367 max(value: NativeDate, message: string): this;
368
369 /** Sets a minimum date validator. */
370 min(value: NativeDate, message: string): this;
371
372 /** Default options for this SchemaType */
373 defaultOptions: Record<string, any>;
374 }
375
376 class Decimal128 extends SchemaType {
377 /** This schema type's name, to defend against minifiers that mangle function names. */
378 static schemaName: 'Decimal128';
379
380 /** Default options for this SchemaType */
381 defaultOptions: Record<string, any>;
382 }
383
384 class DocumentArray extends SchemaType implements AcceptsDiscriminator {
385 /** This schema type's name, to defend against minifiers that mangle function names. */
386 static schemaName: 'DocumentArray';
387
388 static options: { castNonArrays: boolean; };
389
390 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
391 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
392
393 /** The schema used for documents in this array */
394 schema: Schema;
395
396 /** The constructor used for subdocuments in this array */
397 caster?: typeof Types.Subdocument;
398
399 /** Default options for this SchemaType */
400 defaultOptions: Record<string, any>;
401 }
402
403 class Map extends SchemaType {
404 /** This schema type's name, to defend against minifiers that mangle function names. */
405 static schemaName: 'Map';
406
407 /** Default options for this SchemaType */
408 defaultOptions: Record<string, any>;
409 }
410
411 class Mixed extends SchemaType {
412 /** This schema type's name, to defend against minifiers that mangle function names. */
413 static schemaName: 'Mixed';
414
415 /** Default options for this SchemaType */
416 defaultOptions: Record<string, any>;
417 }
418
419 class Number extends SchemaType {
420 /** This schema type's name, to defend against minifiers that mangle function names. */
421 static schemaName: 'Number';
422
423 /** Sets a enum validator */
424 enum(vals: number[]): this;
425
426 /** Sets a maximum number validator. */
427 max(value: number, message: string): this;
428
429 /** Sets a minimum number validator. */
430 min(value: number, message: string): this;
431
432 /** Default options for this SchemaType */
433 defaultOptions: Record<string, any>;
434 }
435
436 class ObjectId extends SchemaType {
437 /** This schema type's name, to defend against minifiers that mangle function names. */
438 static schemaName: 'ObjectId';
439
440 /** Adds an auto-generated ObjectId default if turnOn is true. */
441 auto(turnOn: boolean): this;
442
443 /** Default options for this SchemaType */
444 defaultOptions: Record<string, any>;
445 }
446
447 class Subdocument<DocType = unknown> extends SchemaType implements AcceptsDiscriminator {
448 /** This schema type's name, to defend against minifiers that mangle function names. */
449 static schemaName: string;
450
451 /** The document's schema */
452 schema: Schema;
453
454 /** Default options for this SchemaType */
455 defaultOptions: Record<string, any>;
456
457 discriminator<T, U>(name: string | number, schema: Schema<T, U>, value?: string): U;
458 discriminator<D>(name: string | number, schema: Schema, value?: string): Model<D>;
459
460 cast(val: any, doc?: Document<any>, init?: boolean, prev?: any, options?: any): HydratedSingleSubdocument<DocType>;
461 }
462
463 class String extends SchemaType {
464 /** This schema type's name, to defend against minifiers that mangle function names. */
465 static schemaName: 'String';
466
467 /** Adds an enum validator */
468 enum(vals: string[] | any): this;
469
470 /** Adds a lowercase [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
471 lowercase(shouldApply?: boolean): this;
472
473 /** Sets a regexp validator. */
474 match(value: RegExp, message: string): this;
475
476 /** Sets a maximum length validator. */
477 maxlength(value: number, message: string): this;
478
479 /** Sets a minimum length validator. */
480 minlength(value: number, message: string): this;
481
482 /** Adds a trim [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
483 trim(shouldTrim?: boolean): this;
484
485 /** Adds an uppercase [setter](http://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-set). */
486 uppercase(shouldApply?: boolean): this;
487
488 /** Default options for this SchemaType */
489 defaultOptions: Record<string, any>;
490 }
491
492 class UUID extends SchemaType {
493 /** This schema type's name, to defend against minifiers that mangle function names. */
494 static schemaName: 'UUID';
495
496 /** Default options for this SchemaType */
497 defaultOptions: Record<string, any>;
498 }
499 }
500 }
501}
502
\No newline at end of file