Hooks not triggering when inserting raw queries via sequelize.query()

六眼飞鱼酱① 提交于 2021-01-28 06:36:00

问题


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);

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


回答1:


Your hooks won't be called until you use model's function for DB operation , so if you are running raw query , hooks will never be fired,

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;

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.



来源:https://stackoverflow.com/questions/53386132/hooks-not-triggering-when-inserting-raw-queries-via-sequelize-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!