我想创建一种使用bcrypt.compare()
下面的代码来验证用户密码的方法。
UserSchema.methods.validatePassword = async (data) => {
console.log(this.email); // returns undefined
console.log(this.first_name); // returns undefined
return await bcrypt.compare(data, this.password);
};
这是我创建的UserSchema
const UserSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
},
{ timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);
当进入this.password
我的模式时,.pre('save', ..)
它可以工作,但是当我使用模式方法时,显示未定义。:(
这是该方法的实现
const verifySignIn = async (req, res, next) => {
const { email, password } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({
status: 'failed',
message: 'User Not found.',
});
}
const isValid = await user.validatePassword(password);
if (!isValid) {
return res.status(401).send({
message: 'Invalid Password!',
data: {
user: null,
},
});
}
next();
} catch (err) {
Server.serverError(res, err);
}
};
在指南中说:
千万不能使用ES6箭头函数声明的方法(
=>
)。箭头函数显式阻止绑定this
,因此您的方法将无权访问文档...
因此,在这种情况下,您只需更改UserSchema.methods.validatePassword = async (data) => {...
为UserSchema.methods.validatePassword = async function(data) {...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句