How can I activate hook beforeCreate when calling bulkCreating in Sequelize?

I have a beforeCreate hook in the Sequelize model (runs bcrypt in the password in the User table) and would like to create a user in the seed file. Functions such as bulkCreate are simply inserted into the database and therefore do not cause any hooks (including createdAt / updatedAt ). How to create using hooks called up in a way that matches the format required by the drill?

It seems like many just use sequelize-fixtures ? Is that the way? Or could I just ignore the seed format and use the standard .create / .build and .save format?

Also, where is the documentation related to the visit? Google searches were pretty easy in terms of information.

+6
source share
1 answer

Set individualHooks to true when bulkCreating as shown below:

 User.bulkCreate(users, {individualHooks: true}).then(function() { console.log("Done!"); }); 

There is some (but not enough) documentation about this option here .

In addition, if you allow users to change passwords, you must add beforeUpdate hook. You can prevent bcrypt from being processed with the password twice (when the properties of a user other than the password are updated) as follows:

 function hashPassword(user, options, fn) { //Don't hash if password is already hashed if (user.dataValues.password.indexOf('$2a$') === 0) { fn(null, user); return; } bcrypt.hash(user.password, 10, function(err, hash) { if (err) { console.log('Error while generating hash!'); fn(err, null); return; } user.password = hash; fn(null, user); }); } 
+5
source

All Articles