如何检查是否在sequelize的钩子上发送了特定字段?

时间:2019-02-04 02:04:48

标签: node.js sequelize.js

我正在使用User模型上的beforeUpdate钩子来对更改后的密码进行哈希处理。但是,只要发送任何字段,它都会更改密码。在返回挂钩函数之前,如何检查密码是否已发送?

我试图将退货放在if(user.password !== '')内。但是它不起作用,可能是因为它引用了存储的密码。

这是我的代码:

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

2 个答案:

答案 0 :(得分:0)

您可以像这样使用它:

User.beforeCreate((user, options) => {
    // user.password // Will check if field is there or not
    // user.password != "" // check if empty or not
    user.password = user.password && user.password != "" ? bcrypt.hashSync(user.password, 10) : "";
})

答案 1 :(得分:0)

正确的方法是在模型定义中使用afterValidate钩子,如下所示-

// Create hash for password, on before create/update, using bcrypt
User.afterValidate((user) => {
  user.password = bcrypt.hashSync(user.password,10);
})

调用钩子的顺序-

(1)
  beforeBulkCreate(instances, options)
  beforeBulkDestroy(options)
  beforeBulkUpdate(options)
(2)
  beforeValidate(instance, options)

[... validation happens ...]

(3)
  afterValidate(instance, options)
  validationFailed(instance, options, error)
(4)
  beforeCreate(instance, options)
  beforeDestroy(instance, options)
  beforeUpdate(instance, options)
  beforeSave(instance, options)
  beforeUpsert(values, options)

[... creation/update/destruction happens ...]

(5)
  afterCreate(instance, options)
  afterDestroy(instance, options)
  afterUpdate(instance, options)
  afterSave(instance, options)
  afterUpsert(created, options)
(6)
  afterBulkCreate(instances, options)
  afterBulkDestroy(options)
  afterBulkUpdate(options)

更多详细信息here