Hooks not triggering when inserting raw queries via sequelize.query()(通过 sequelize.query() 插入原始查询时未触发挂钩)
问题描述
我有以下用于 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;
};
通过 .sql 文件来为数据库播种#raw-queries" rel="nofollow noreferrer">原始查询:
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 是如何知道的它必须发射钩子.这只有在您使用方法时才有可能喜欢
Reason : You can write anything inside your raw query , select/insert/update/delete anything , how does sequelize.js know that it has to fire the hooks. This is only possible when you use methods like
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() 插入原始查询时未触发挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 sequelize.query() 插入原始查询时未触发挂钩
基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01