title: Getters and Setters for Virtual fields in Sequelize
body: <p>I'm trying to hash my password field before storing it in the database. For that reason I've created a virtual field called password and an actual field called <code>hashedPassword</code>. The trouble is that when I try to encrypt the password in <code>beforeCreate</code> hook, it the <code>user.password</code> is undefined. I have tried every thing. I've also defined custom getters and setters for the virtual field. I don't know what I'm doing wrong here. Any help or guidance would be appreciated. Thanks.</p>
  
  <pre class="lang-js prettyprint-override"><code>import bcrypt from 'bcrypt';
  
  module.exports = (sequelize, DataTypes) =&gt; {
    const User = sequelize.define(
      'User',
      {
          passwordhash: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
              notEmpty: true
            }
          },
          password: {
            allowNull: false,
            type: DataTypes.VIRTUAL,
            set(password) {
              const valid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&amp;]).{8,30}$/.test(
                password
              );
              if (!valid) {
                throw new Error(`Password not valid ${password}`);
              }
              this.setDataValue('password', password);
            },
            get() {
              return this.getDataValue('password');
            }
          }
        }
      },
      {
        hooks: {
          beforeCreate: function hashPassword(user) {
            console.log('user is:', user);
            return bcrypt
              .hash('Abcdefgh1@', 12)
              .then(hashed =&gt; {
                user.passwordhash = hashed;
              })
              .catch(error =&gt; error);
          }
        }
      }
    );
    User.associate = function(models) {
      // associations can be defined here
    };
    return User;
  };
  
  
  </code></pre>