node.js 在 Sequelize 中使用实例方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19433824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Instance Methods in Sequelize
提问by surfearth
Can someone help me understand how to use instance methods in 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. When I try to call the code in the REPL, after having imported the user model and synced the DB, I get the following:
有人可以帮助我了解如何在 Sequelize 中使用实例方法吗?我已经查看了文档,但发现它很稀疏。目前,我正在尝试在我的用户模型上使用 setPassword 和 verifyPassword 实例方法。当我尝试在 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);
});
}
}
});
};
采纳答案by SergeS
Instance method can be used on specific element instances eg.
实例方法可用于特定元素实例,例如。
models.User.find(123).success( function( user ) {
user.setPassword('test');
});
回答by Pyro
You define the function as:
function(password, done)
您将函数定义为:
function(password, done)
Yet you don't supply the done parameter. Thus, the function leaves done as undefined and calling done() is executing an undefined function.
但是您没有提供 done 参数。因此,该函数将 done 保留为未定义,调用 done() 正在执行一个未定义的函数。
You could fix this in 3 ways:
您可以通过 3 种方式解决此问题:
- Default done to a noop function
function () {} - Only return
done()if done is defined - Supply a done callback when calling the instance function.
- 默认完成一个 noop 函数
function () {} - 仅
done()在定义完成时返回 - 调用实例函数时提供完成回调。
The alternative is to refactor it to return a promise which it resolves on completion.
另一种方法是重构它以返回它在完成时解决的承诺。

