我正在尝试使用关键字 this
访问存储在用户实例中的密码,但它不起作用?
这是我调用时的代码。
Users.find({where: {$or: [{ email: email} ,{ username: username }]}})
.then(user => {
if (!user) return res.status(401).send(new errors.Unauthorized('Email/Username or Password Not Found!'));
user.authenticate(password, (err, match) => {
if (err) return res.status(401).send(err);
res.send(user);
});
})
.catch(err => res.send(err));
这是我的实例方法的代码。
instanceMethods :{
authenticate: (password, cb) => {
return bcrypt.compare(password, this.password, (err, match) => {
if (err) return cb(new errors.Unauthorized());
return cb(null, match);
});
}
}
最佳答案
您使用箭头函数,它不会让 this
通过 call()
或 apply()
进行绑定(bind)。参见 MDN :
Since this is not bound in arrow functions, the methods call() or apply() can only pass in parameters. this is ignored.
此外,
As stated previously, arrow function expressions are best suited for non-method functions...
请参阅此 github 问题 https://github.com/sequelize/sequelize/issues/5858
There is no way to override the scope of arrow functions - that's one of their main features. So there's nothing we can do here
关于javascript - Sequelize 实例方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43546690/