Sequelize, a custom setter, does not install

Unfortunately, the documentation for developers of the properties of models and getters is somewhat inadequate, and I had problems with the work of my little setter.

var bcrypt = require('bcrypt');

module.exports = function( sequelize, DataTypes )
{
    var User = sequelize.define('User', {
        username:       { type:DataTypes.STRING, unique: true, allowNull: false },
        email:          { type:DataTypes.STRING, allowNull: false, unique: true },
        userlevel:      { type:DataTypes.INTEGER, allowNull:false, defaultValue:0 },
        password:       { type:DataTypes.STRING, 
            set: function(v) {
                var pw = this;
                var r;
                bcrypt.genSalt(10, function(err,salt) {
                    bcrypt.hash(v, salt, function(err,hash) {
                        pw.setDataValue('password', hash);
                    });
                });
            } }
    });



    return User;
}

Now from what I can tell based on github problems, custom property settings are not called when creating (), so the call

db.User.create( { username:'guest', email:'guest@guest', userlevel:1, password:'guest' } ).success( function(record) { console.log(record) });

the following insert is output:

Executing (default): INSERT INTO `Users` (`id`,`username`,`email`,`userlevel`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'guest','guest@guest',100,'2014-02-25 01:05:17','2014-02-25 01:05:17');

so I went ahead and added the following to the success clause:

u.set('password', 'stupid');
u.save();

I see that my setter gets the correct name and that the hash is set in the password property. However, as soon as the setter finishes, and I return back to my u.save () line, the u-object returns to its previous state without a password.

Any ideas?

+4
1

, . , :

var User = sequelize.define('User', {
    username:       { type: DataTypes.STRING,  allowNull: false, unique: true   },
    email:          { type: DataTypes.STRING,  allowNull: false, unique: true   },
    userlevel:      { type: DataTypes.INTEGER, allowNull:false,  defaultValue:0 },
    password:       {
        type: Sequelize.STRING,
        set:  function(v) {
            var salt = bcrypt.genSaltSync(10);
            var hash = bcrypt.hashSync(v, salt);

            this.setDataValue('password', hash);
        }
    }
})
+12

All Articles