Validating password / confirm password with Mongoose schema

前端 未结 7 2165
小蘑菇
小蘑菇 2020-12-08 17:15

I have a userSchema that looks like this:

var userSchema = new Schema({
    name: {
      type: String
    , required: true
    , validate: [val         


        
7条回答
  •  执念已碎
    2020-12-08 17:38

    You can attach custom methods to your model instances by adding new function attributes to Schema.methods (you can also create Schema functions using Schema.statics.) Here's an example that validates a user's password:

    userSchema.methods.checkPassword = function(password) {
        return (hash(password) === this.password);
    };
    
    // You could then check if a user's password is valid like so:
    UserModel.findOne({ email: 'email@gmail.com' }, function(err, user) {
        if (user.checkPassword('secretPassword')) {
            // ... user is legit
        }
    });
    

提交回复
热议问题