The best way is to extend the model using class or instance methods:
var User = sequelize.define('User', { username: { type: Sequelize.STRING, unique: true }, email: { type: Sequelize.STRING, unique: true }, password: Sequelize.STRING, token: Sequelize.STRING }, { instanceMethods: { comparePassword : function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.getDataValue('password'), function(err, isMatch) { if(err) return cb(err); cb(null, isMatch); }); }, setToken: function(){
So when you do
User.build({ firstname: 'foo', lastname: 'bar' }).getFullname(); // 'foo bar'
So, to set the token, you can do it like this:
User.build({ ... }).setToken().save();
Or, to use the comparePassword function:
User.find({ ... }).success(function(user) { user.comparePassword('the password to check', function(err, isMatch) { ... } });
This can be seen in Sequelize docs.
Edit
The latest versions have hooks for each model, you can check the documentation for hooks that are very simple and complement their class or instance.
Dan rocha
source share