简体   繁体   中英

How to compare passwords in a mongoose schema?

How can I compare password and password_confirmation , and if they don't match then I'll print "Passwords don't match" to the error message?

const userSchema = new Schema(
  {
    username: {type: String, required: [true, "Please enter a username"], unique: [true, "Username taken"]},
    password: {type: String, required: true, minLength: [8, "Minimum password lenth is 8"]},
    password_confirmation: {type: String}
  },
  { timestamps: true }
);

You can use validator in your schema. https://www.npmjs.com/package/validator

passwordConfirm: {
type: String,
required: [true, 'Please confirm ypur password'],
validate: {
  // this only works on CREATE and  SAVE!!!!
  validator: function (el) {
    return el === this.password;
  },
  message: 'Password are not the same',
},

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM