Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  40] [ 1]  / answers: 1 / hits: 23971  / 11 Years ago, thu, october 17, 2013, 12:00:00

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:



> 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);
});
}
}
});
};

More From » node.js

 Answers
3

Instance method can be used on specific element instances eg.



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

[#74919] Wednesday, October 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dallasb

Total Points: 657
Total Questions: 98
Total Answers: 97

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;