猫鼬模式方法根据传递的输入检查密码

时间:2018-11-04 04:45:59

标签: mongoose

我在理解如何在猫鼬模式Person上使用比较密码时遇到麻烦。我有一个登录路径,该路径根据电子邮件匹配检索一条记录。

var Person = require('../models/person.js');

exports.login = function (req, res) {
    const email = req.body.email;
    Person.findOne({ email }, function (err, user) {
        if(err){
            res.status(501).send(error);
        }
        if(!user){
            res.status(401);
        }
        if(user){
            console.log(typeof user)
           // const test = new Person(user);
            user.comparePassword(req.body.password, (err, isMatch) => {
  
            });

        }
    })
}

personSchema.methods.comparePassword = function(password, done) {
  bcrypt.compare(password, this.password, function(err, isMatch) {
    done(err, isMatch);
  });
};

我正在尝试调用comparePassword方法,但是this.password为null以下是Person的架构。

var personSchema = new Schema({
  first       :   {type: String, required: 'FirstNameInvalid'},
  last        :   String,
  email       :   {type: String, unique: true, lowercase: true, required: 'EmailInvalid'},
  password    :   {type: String, select: false, required: 'PasswordInvalid'}
});

1 个答案:

答案 0 :(得分:1)

仅当您使用select: false击中登录路径时,您才能覆盖select()

exports.login = function (req, res) {
    const email = req.body.email;
    Person.findOne({ email })
        .select('password')
        .exec(function (err, user) {
            if(err){
                res.status(501).send(error);
            }
            if(!user){
                res.status(401);
            }
            if(user){
                console.log(typeof user)
                user.comparePassword(req.body.password, (err, isMatch) => {

                });

            }
    });
}