I have a beforeCreate
hook in a Sequelize model (runs bcrypt on the password in a User
table), and would like to create a user in the seed file. Functions like bulkCreate simply insert into the database, and so don't call any hooks (including the createdAt
/updatedAt
). How do I create with the hooks called in a way that matches the format required by the seeder?
It seems like many are just using sequelize-fixtures
? Is this the way to go? Or I could just ignore the seed format, and use the standard .create/.build and .save format?
Also, where is documentation related to seeding located? The Google searches were pretty light in terms of info.
Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a beforeUpdate hook. Note: You can't use hooks with instances. Hooks are used with models.
Sequelize hooks are lifecycle events that get executed during a specific period of time. These hooks are JavaScript functions that run before or after an operation has been completed by Sequelize. Let's see an easy example that demonstrates one of the hooks in action.
When you need to insert multiple rows to your SQL database table, you can use the Sequelize bulkCreate() method. The bulkCreate() method allows you to insert multiple records to your database table with a single function call.
Set the individualHooks
option to true when bulkCreating, as below:
User.bulkCreate(users, {individualHooks: true}).then(function() {
console.log("Done!");
});
There's some documentation about this option here.
Also, if you're allowing users to change passwords, you should add a beforeUpdate
hook as well. You can prevent the password from being processed by bcrypt two times (when properties of the User other than the password are updated) in the following way:
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With