Skip to content

Commit

Permalink
fix(types): set this to doc type in SchemaType.prototype.validate()
Browse files Browse the repository at this point in the history
Fix #12590
  • Loading branch information
vkarpov15 committed Nov 7, 2022
1 parent ae14d0e commit 6c78334
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
18 changes: 18 additions & 0 deletions test/types/schema.test.ts
Expand Up @@ -897,3 +897,21 @@ function gh12562() {
}
);
}

function gh12590() {
const UserSchema = new Schema({
_password: String
});

type User = InferSchemaType<typeof UserSchema>;

expectType<SchemaType<User>>(UserSchema.path('hashed_password'));

UserSchema.path('hashed_password').validate(function(v: any) {
expectType<HydratedDocument<User>>(this);
if (this._password && this._password.length < 8) {
this.invalidate('password', 'Password must be at least 8 characters.');
}
});

}
2 changes: 1 addition & 1 deletion types/index.d.ts
Expand Up @@ -258,8 +258,8 @@ declare module 'mongoose' {
obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>>;

/** Gets/sets schema paths. */
path<ResultType extends SchemaType = SchemaType<any, HydratedDocument<DocType, TInstanceMethods>>>(path: string): ResultType;
path<pathGeneric extends keyof EnforcedDocType>(path: pathGeneric): SchemaType<EnforcedDocType[pathGeneric]>;
path<ResultType extends SchemaType = SchemaType>(path: string): ResultType;
path(path: string, constructor: any): this;

/** Lists all paths and their type in the schema. */
Expand Down
10 changes: 7 additions & 3 deletions types/schematypes.d.ts
Expand Up @@ -188,7 +188,11 @@ declare module 'mongoose' {
[other: string]: any;
}

class SchemaType<T = any> {
interface Validator {
message?: string; type?: string; validator?: Function
}

class SchemaType<T = any, DocType = any> {
/** SchemaType constructor */
constructor(path: string, options?: AnyObject, instance?: string);

Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 6c78334

Please sign in to comment.