通过 sequelize.query() 插入原始查询时钩子不触发

编程入门 行业动态 更新时间:2024-10-28 09:24:23
本文介绍了通过 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); } } } }

这不起作用,因为我在重新播种后仍然获得纯文本值 - 我应该寻找另一种方式吗?我正在研究 sequelize 大写名称,然后保存在数据库中 - 实例钩子

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() 插入原始查询时钩子不触发

本文发布于:2023-10-13 14:35:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488228.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:钩子   原始   sequelize   query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!