最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 2浏览 0评论

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

我正在使用我的用户模型上的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
回答如下:

您可以这样使用它:

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) : "";
})

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

我正在使用我的用户模型上的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
回答如下:

您可以这样使用它:

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)

  1. 暂无评论