使用BCrypt和Sequelize模型

我试图用我的sequelize模型使用bcrypt-nodejs包,并试图按照教程将哈希合并到我的模型中,但是我在generateHash得到一个错误。 我似乎无法弄清楚这个问题。 有没有更好的方法来joinbcrypt?

错误:

 /Users/user/Desktop/Projects/node/app/app/models/user.js:26 User.methods.generateHash = function(password) { ^ TypeError: Cannot set property 'generateHash' of undefined at module.exports (/Users/user/Desktop/Projects/node/app/app/models/user.js:26:27) at Sequelize.import (/Users/user/Desktop/Projects/node/app/node_modules/sequelize/lib/sequelize.js:641:30) 

模型:

 var bcrypt = require("bcrypt-nodejs"); module.exports = function(sequelize, DataTypes) { var User = sequelize.define('users', { annotation_id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, firstName: { type: DataTypes.DATE, field: 'first_name' }, lastName: { type: DataTypes.DATE, field: 'last_name' }, email: DataTypes.STRING, password: DataTypes.STRING, }, { freezeTableName: true }); User.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; User.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; return User; } 

       

网上收集的解决方案 "使用BCrypt和Sequelize模型"

方法应该在sequelize.define的“options”参数中sequelize.define

 const bcrypt = require("bcrypt"); module.exports = function(sequelize, DataTypes) { const User = sequelize.define('users', { annotation_id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, firstName: { type: DataTypes.DATE, field: 'first_name' }, lastName: { type: DataTypes.DATE, field: 'last_name' }, email: DataTypes.STRING, password: DataTypes.STRING }, { freezeTableName: true, instanceMethods: { generateHash(password) { return bcrypt.hash(password, bcrypt.genSaltSync(8)); }, validPassword(password) { return bcrypt.compare(password, this.password); } } }); return User; } 

其他的select:使用钩子和bcryptasynchronous模式

 User.beforeCreate((user, options) => { return bcrypt.hash(user.password, 10) .then(hash => { user.password = hash; }) .catch(err => { throw new Error(); }); });