Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types): set this to doc type in SchemaType.prototype.validate() #12663

Merged
merged 2 commits into from Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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) {
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
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