简体   繁体   English

在Sequelize中使用实例方法

[英]Using Instance Methods in Sequelize

Can someone help me understand how to use instance methods in Sequelize? 有人可以帮我理解如何在Sequelize中使用实例方法吗? I've reviewed the documentation but have found it to be sparse. 我已经查看了文档,但发现它很稀疏。 At present, I am trying to use setPassword and verifyPassword instance methods on my user model. 目前,我正在尝试在我的用户模型上使用setPassword和verifyPassword实例方法。 When I try to call the code in the REPL, after having imported the user model and synced the DB, I get the following: 当我尝试在REPL中调用代码时,在导入用户模型并同步数据库之后,我得到以下内容:

> models.User.setPassword('test');
TypeError: Object [object Object] has no method 'setPassword'

Here is the code for the user model: 以下是用户模型的代码:

var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('User', {
    email: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { isEmail: true } },
    password: { type: DataTypes.STRING, allowNull: false},
    firstName: {type: DataTypes.STRING},
    lastName: {type: DataTypes.STRING},
    companyName: {type: DataTypes.STRING},
    admin: {type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false,},
    forgotUrl: {type: DataTypes.STRING, unique: true},
    forgotDate: {type: DataTypes.STRING},
    lastLogin: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW
    }
  }, {
    paranoid: true,
    instanceMethods: {
      setPassword: function(password, done) {
        return bcrypt.genSalt(10, function(err, salt) {
          return bcrypt.hash(password, salt, function(error, encrypted) {
            this.password = encrypted;
            this.salt = salt;
            return done();
          });
        });
      },
      verifyPassword: function(password, done) {
        return bcrypt.compare(password, this.password, function(err, res) {
          return done(err, res);
        });
      }
    }
  });
};

Instance method can be used on specific element instances eg. 实例方法可以用于特定元素实例,例如。

models.User.find(123).success( function( user ) { 
    user.setPassword('test');
});

You define the function as: function(password, done) 您将函数定义为: function(password, done)

Yet you don't supply the done parameter. 但是你没有提供done参数。 Thus, the function leaves done as undefined and calling done() is executing an undefined function. 因此,函数将作为未定义完成,并且调用done()正在执行未定义的函数。

You could fix this in 3 ways: 您可以通过3种方式解决此问题:

  1. Default done to a noop function function () {} 默认完成noop函数function () {}
  2. Only return done() if done is defined 只有在定义完成后才返回done()
  3. Supply a done callback when calling the instance function. 调用实例函数时提供完成回调。

The alternative is to refactor it to return a promise which it resolves on completion. 另一种方法是重构它以返回它在完成时解析的承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM