Sean
Sean

Reputation: 517

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

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

Upvotes: 4

Views: 1927

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

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.

Upvotes: 4

Related Questions