Home > Net >  How to use validator in mongoose schema in typescipt?
How to use validator in mongoose schema in typescipt?

Time:09-28

I was using a validator to validate my passwordConfirm matching with a password. It was working fine on js but now as I am moving to ts I am facing an error. Please solve my issue Thanks.

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'.

CodePudding user response:

First, you should not save passwordConfirm field in the schema. passwordConfirm should just be used for validation on the backend. The correct way to do this;

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();
});
  • Related