似乎没有调用beforeUpdate

Mag*_*gix 6 javascript passwords hook node.js sequelize.js

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

'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;
};
Run Code Online (Sandbox Code Playgroud)

它在用户创建方面非常有效,但beforeUpdate钩子似乎不起作用或被调用,并且密码以纯文本形式保存在数据库中.

它来自何处以及如何修复?

Ung*_*ilz 7

你是如何更新用户的?获取用户实例并更新它并通过查询模型进行更新之间存在差异.前者是实例更新,后者是批量更新操作(即使您的where过滤器将返回单个项目).

这种区别很重要,因为它beforeUpdate是一个实例挂钩,因此它只能在实例更新时触发.您可以更改更新用户的方式或实现beforeBulkUpdate挂钩.