sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

The function 'bulkCreate' doesn't call the hook 'afterCreate' if 'afterBulkCreate' isn't declared

Open yuredd opened this issue 10 years ago • 2 comments

Sorry I'm fairly new to nodejs and javascript in general so I wasn't able to create a failing unit test at the time, I'm working on it!

  • What you are doing?

I'm trying to update a field on every row after a bulkCreate Post a minimal code sample that reproduces the issue, including models and associations

var Invitation = sequelize.define('Invitation', {
  from: {type: Sequelize.STRING, validate: {isEmail: true}},
  to: {type: Sequelize.STRING, validate: {isEmail: true}},
  hash: Sequelize.STRING,
  used: {type: Sequelize.INTEGER, deafultValue: 0}
}, {
    instanceMethods: {
        createHash: function() {
            this.hash = shortid.generate();
            this.save();
        }
    },
    hooks: {
        afterBulkCreate: function(instances, options) {
        },
        afterCreate: function(instance, options, fn) {
            instance.createHash();
        },
    }
});

sequelize.sync({force: true}).then(function() {
    Invitation.bulkCreate([{from: '[email protected]'}]);
    return null;
});
  • What do you expect to happen?

I expect that afterCreate will be called for every row in the bulk insert.

  • What is actually happening?

if I remove the afterBulkCreate the afterCreate never gets called but if i leave the afterBulkCreate sequelize will call both afterBulkCreate and afterCreate.

  • Which dialect you are using (postgres, mysql etc)?

sqlite

  • Which sequelize version you are using?

Im using 3.15.1

yuredd avatar Dec 30 '15 14:12 yuredd

That is expected, in most cases bulkCreate will attempt to use a single bulk insert statement which makes afterCreate hooks impossible in most cases since you don't have a primary key available.

You can use the option individualHooks: true to have Sequelize create each row individually and also fire hooks.

mickhansen avatar Jan 04 '16 08:01 mickhansen

Thanks for the help, with your indication I can do what I was trying todo. Thanks for this great library!

yuredd avatar Jan 05 '16 20:01 yuredd