以下是我的架构:-
var Sequelize = require('sequelize');
var bcrypt = require('bcrypt');
var jwt = require('jsonwebtoken');
var sequelize = new Sequelize('postgres://postgres:root@localhost/DB');
var User = sequelize.define('users', {
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
}
}, {
hooks: {
beforeCreate: (user) => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
},
generateJWT: function() {
var today = new Date();
var exp = new Date(today);
exp.setDate(today.getDate() + 60);
return jwt.sign({
id: this._id,
username: this.username,
exp: parseInt(exp.getTime() / 1000),
}, secret);
},
toAuthJSON: function(){
return {
username: this.username,
email: this.email,
token: this.generateJWT(),
};
}
}
});
sequelize.sync()
.then(() => console.log('users table has been successfully created, if one doesn\'t exist'))
.catch(error => console.log('This error occured', error));
module.exports = User;
当我使用以下代码时:-
User.findOne({ where: { username: req.body.user.username } }).then(function(user){
if(!user){
User.create({
username: req.body.user.username,
email: req.body.user.email,
password: req.body.user.password})
.then(user => {
return res.json({user: user.toAuthJSON()}); ---------> Unable to access toAuthJSON()
})
.catch(error => {
res.status(400).json({errors: {error: error}});
});
}
如上所示,无法访问实例方法toAuthJSON()。因此,请帮助我解决此问题。我被困住了。在某处读取了实例方法已被贬值的地方,但是我仍然能够在自己的模式中对其进行定义。我的续集版本是4.38.0