Linked Questions

Popular Questions

I'm using a beforeUpdate hook on my User model to hash the password when its changed. But its changing the password whenever any field is sent. How can I check if the password was sent before return the hooks function?

I tried to place the return inside a if(user.password !== ''). But its doesn't work, probably because its referring to the stored password.

Here is my code:

const Sequelize = require('sequelize')
const connection = require('../../../db/connection.js')

const bcrypt = require('bcrypt')

const User = connection.define('user', {
  fullName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
    validate: { isEmail: true }
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false
  }
})

// Create hash for password, on before create, using bcrypt
User.beforeCreate((user, options) => {
  return bcrypt.hash(user.password, 10).then(hash => {
    user.password = hash
  })
})

// Create hash for password, on before update, using bcrypt
User.beforeUpdate((user, options) => {
  return bcrypt.hash(user.password, 10).then(hash => {
    user.password = hash
  })
})

module.exports = User

Related Questions