diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index b0e148afce5..6bf7bcd94d2 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -897,3 +897,21 @@ function gh12562() { } ); } + +function gh12590() { + const UserSchema = new Schema({ + _password: String + }); + + type User = InferSchemaType; + + expectType>(UserSchema.path('hashed_password')); + + UserSchema.path('hashed_password').validate(function(v) { + expectType>(this); + if (this._password && this._password.length < 8) { + this.invalidate('password', 'Password must be at least 8 characters.'); + } + }); + +} diff --git a/types/index.d.ts b/types/index.d.ts index 97663a46d84..4f7cc0e1393 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -258,8 +258,8 @@ declare module 'mongoose' { obj: SchemaDefinition>; /** Gets/sets schema paths. */ + path>>(path: string): ResultType; path(path: pathGeneric): SchemaType; - path(path: string): ResultType; path(path: string, constructor: any): this; /** Lists all paths and their type in the schema. */ diff --git a/types/schematypes.d.ts b/types/schematypes.d.ts index 093651d1408..513037cffe5 100644 --- a/types/schematypes.d.ts +++ b/types/schematypes.d.ts @@ -188,7 +188,11 @@ declare module 'mongoose' { [other: string]: any; } - class SchemaType { + interface Validator { + message?: string; type?: string; validator?: Function + } + + class SchemaType { /** SchemaType constructor */ constructor(path: string, options?: AnyObject, instance?: string); @@ -270,10 +274,10 @@ declare module 'mongoose' { unique(bool: boolean): this; /** The validators that Mongoose should run to validate properties at this SchemaType's path. */ - validators: { message?: string; type?: string; validator?: Function }[]; + validators: Validator[]; /** Adds validator(s) for this document path. */ - validate(obj: RegExp | Function | any, errorMsg?: string, type?: string): this; + validate(obj: RegExp | ((this: DocType, value: any, validatorProperties?: Validator) => any), errorMsg?: string, type?: string): this; } namespace Schema {