[英]How to use instance methods on sequelize
Can someone help me figure out how to use my sequelize
instance methods on my controller? 有人可以帮我弄清楚如何在控制器上使用我的
sequelize
实例方法吗?
I wrote my model like that: 我这样写我的模型:
const bcrypt = require('bcryptjs');
module.exports = (sequelize, Sequelize) => {
const Patient = sequelize.define('Patient', {
email: {
type: Sequelize.STRING,
allowNull: false,
},
password : {
type: Sequelize.STRING,
allowNull: false,
},
}, {
classMethods: {
associate: (models) => {
// associations can be defined here
}
},
instanceMethods: {
generateHash: function (password) {
return bcrypt.hash(password, 8, function(err, hash){
if(err){
console.log('error'+err)
}else{
return hash;
}
});
},
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
}
}
});
return Patient;
};
but when I launch it on my controller which I made like that 但是当我在控制器上启动它时
const jwt = require('jsonwebtoken');
const passport = require('passport');
const Patient = require('../models').Patient;
module.exports = {
///
create(req, res) {
return Patient
.create({
email: req.body.email,
password: Patient.prototype.generateHash(req.body.password)
})
.then(patient => res.status(201).send(patient))
.catch(error => res.status(400).send(error));
},
};
I get this error for the request: 我收到此错误消息:
TypeError: Cannot read property 'generateHash' of undefined
TypeError:无法读取未定义的属性“ generateHash”
First of all you should use bcrypt.hashSync()
because you want to assign asynchronous function call to the password
- it won't work. 首先,您应该使用
bcrypt.hashSync()
因为您想将异步函数调用分配给password
-该password
将无法使用。
generateHash: function(password){
try {
return bcrypt.hashSync(password, 8);
} catch (e) {
console.log('error: ' + e);
}
}
In order to use instance method you should do 为了使用实例方法,您应该做
Patient.build().generateHash(req.body.password);
build()
creates new instance of model so then you can run the instance method. build()
创建模型的新实例,因此您可以运行实例方法。 Or you can declare the generateHash
as a class method so you could run it like that 或者,您可以将
generateHash
声明为类方法,以便像这样运行它
Patient.generateHash(req.body.password);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.