我正在使用驗證器來驗證我的密碼確認是否與密碼匹配。它在 js 上運行良好,但現在當我轉向 ts 時,我遇到了一個錯誤。請解決我的問題謝謝。
const UserSchema = new Schema(
{
password: {
type: String,
required: [true, 'Password is required'],
},
passwordConfirm: {
type: String,
required: [true, 'PasswordConfirm is required'],
validate: {
// This only works on CREATE and SAVE!!!
validator(el: string) {
return el === this.password; // error on this line on "this" keyword
},
message: 'Passwords are not the same!',
},
},
}
and this is the error i am facing
Property 'password' does not exist on type 'Function | String | RegExp | { [path: string]: SchemaDefinitionProperty<undefined>; } | typeof SchemaType | Schema<any, any, any> | ... 18 more ... | ({ ...; } | { ...; })[]'.
Property 'password' does not exist on type 'Function'.
uj5u.com熱心網友回復:
首先,您不應該passwordConfirm在模式中保存欄位。passwordConfirm應該只用于后端驗證。這樣做的正確方法;
UserSchema.pre("save", async function(next) {
if (this.password && this.passwordConfirm) {
let isSame = this.password === this.passwordConfirm;
if(!same){
throw error ("Password and Confirm password did not match")
}
}
next();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/510357.html
