问题描述
我有以下用于 MySQL 数据库的 Employee
模型:
I have the following Employee
model for a MySQL database:
var bcrypt = require('bcrypt');
module.exports = (sequelize, DataTypes) => {
const Employee = sequelize.define(
"Employee",
{
username: DataTypes.STRING,
password: DataTypes.STRING,
}, {}
);
return Employee;
};
通过 :
Seeding the database is done by reading a .sql
file containing 10,000+ employees via raw queries:
sequelize.query(mySeedingSqlFileHere);
问题是 SQL 文件中的密码是纯文本,我想使用 bcrypt
在插入数据库之前对它们进行哈希处理.我以前从未做过批量插入,所以我正在研究 Sequelize docs for向 Employee
模型 添加一个钩子,如下所示:
The problem is that the passwords in the SQL file are plain text and I'd like to use bcrypt
to hash them before inserting into the database. I've never done bulk inserts before so I was looking into Sequelize docs for adding a hook to the Employee
model, like so:
hooks: {
beforeBulkCreate: (employees, options) => {
for (employee in employees) {
if (employee.password) {
employee.password = await bcrypt.hash(employee.password, 10);
}
}
}
}
这不起作用,因为我在重新播种后仍然获得纯文本值 - 我应该寻找另一种方式吗?我正在研究 在保存数据库之前将名称大写 - 实例挂钩
This isn't working as I'm still getting the plain text values after reseeding - should I be looking into another way? I was looking into sequelize capitalize name before saving in database - instance hook
推荐答案
在你使用模型的函数进行数据库操作之前,你的钩子不会被调用,所以如果你运行原始查询,钩子永远不会被触发,
原因:您可以在原始查询中写任何内容,选择/插入/更新/删除任何内容,sequelize.js 是如何知道的它必须发射钩子.这只有在您使用方法时才有可能喜欢
Model.create();
Model.bulkCreate();
Model.update();
Model.destroy;
根据 DOC 原始查询没有要添加的钩子选项.而对于 MODEL 查询您可以检查它是否可以选择启用/禁用挂钩.
And as per DOC raw query doesn't have hooks option to add. And for MODEL queries you can check that it has option to enable/disable hook.
这篇关于通过 sequelize.query() 插入原始查询时未触发挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!