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

问题描述 投票:0回答:2

我正在使用我的用户模型上的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
node.js sequelize.js
2个回答
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) : "";
})

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

© www.soinside.com 2019 - 2024. All rights reserved.