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

Hooks not triggering when inserting raw queries via sequelize.query()(通过 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() 插入原始查询时未触发挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)