beforeUpdate 似乎没有被调用

beforeUpdate doesn't seem to be called

我有一个简单的用户模型如下:

'use strict';

let hashPassword = (user, options) => {
    if (!user.changed('password')) { return; }
    return require('bcrypt')
        .hash(user.getDataValue('password'), 10)
        .then(hash => user.setDataValue('password', hash));
};

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        username: {allowNull: false, type: DataTypes.STRING, unique: true},
        email: {allowNull: false, type: DataTypes.STRING, unique: true},
        password: {allowNull: false, type: DataTypes.STRING, unique: false},
    }, {
        hooks: {
            beforeCreate: hashPassword,
            beforeUpdate: hashPassword
        }
    });
    return User;
};

它在用户创建上非常有效,但是 beforeUpdate 钩子似乎不起作用或被调用,密码以明文形式保存在数据库中。

它来自哪里,如何修复?

您如何更新用户?获取用户实例并更新它与通过查询模型进行更新之间存在差异。前者是 instance 更新,后者是 bulk 更新操作(即使您的 where 过滤器会 return a单个项目)。

这个区别很重要,因为 beforeUpdate 是一个 instance hook,所以它只会在实例更新时触发。您可以更改更新用户的方式,也可以实施 beforeBulkUpdate 挂钩。

提供 Unglückspilz 答案的替代方案。您还可以添加选项

{ individualHooks: true }

Note: methods like bulkCreate do not emit individual hooks by default - only the bulk hooks. However, if you want individual hooks to be emitted as well, you can pass the { individualHooks: true } option to the query call. However, this can drastically impact performance, depending on the number of records involved (since, among other things, all instances will be loaded into memory).

https://sequelize.org/master/manual/hooks.html#model-hooks