我收到一个未定义的字段,尝试比较用户密码
这是功能
logUser = (req,res) => {
User.findOne({ username:req.body.username}, (err,user) => {
if(!user){
req.flash('error','El nombre de usuario no existe');
res.redirect('/login');
}else if(!user.comparePassword(req.body.password)){
req.flash('error','La contraseña no es correcta');
res.redirect('/login');
}else{
res.redirect('/');
}
});
}
在执行if并使用comparePassword
函数时转到else时,架构字段为undefined
架构文件
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
const userSchema = Schema({
username:String,
email:String,
password:String,
registrationDate: {type:Date, defaul: Date.now()}
});
userSchema.methods.encryptPassword = (password) =>{
return bcrypt.hashSync(password, bcrypt.genSaltSync(10));
}
userSchema.methods.comparePassword = (password) =>{
console.log('password: ',this.password);
return bcrypt.compareSync(password, this.password);//here this.password is undefined
}
module.exports = mongoose.model('User',userSchema)
调试时,我发现user
对象不是schem类,而tuis类又是什么呢?
答案 0 :(得分:0)
简而言之,如果您替换它,它将起作用
userSchema.methods.comparePassword = (password) =>{
console.log('password: ',this.password);
return bcrypt.compareSync(password, this.password);//here this.password is undefined
}
使用
userSchema.methods.comparePassword = function(password) {
console.log('password: ',this.password);
return bcrypt.compareSync(password, this.password);//here this.password is undefined
}
由于lexical scoping
中的arrow function
,您正面临问题。 Arrow函数从父级继承其this
范围。