javascript - Sequelize 实例方法不起作用?

标签 javascript postgresql orm this sequelize.js

我正在尝试使用关键字 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/

相关文章:

javascript - 为什么这两个版本的高阶函数没有给出相同的结果?

javascript - 使用类/异步等待时获取未定义的 "this"

postgresql - 如何在 postgresql 交叉表中用零替换空值

java - Spring 3.1 entityManagerFactory java.lang.NoSuchFieldError : NULL Error

python - 我如何使用 Django ORM 执行这个复杂的 SQL 查询? (带连接的子查询)

javascript - 如何通过单击更改多个图像

javascript - Bootstrap 弹出窗口不起作用

SQL - 使用 CTE 或聚合计算指数移动平均线?

ruby-on-rails - Rails 查询选择作为哈希

node.js - Nodejs Bookshelf 中的简单引用关系