Gary
Gary

Reputation: 2339

Sequelize bulkCreate: updateOnDuplicate

I am entering a huge data into the database and I am using this model to apply updateOnDuplicate option to bulkCreate. So I am unable to verify sanity here. My question is since I a unique value with it also be used for the updateOnDuplicate criteria or will be only the primary key that is used to check for duplicates.

The problem is my primary key in the table for the bulkCreate is id which is autoincrement. I have multiple unique values in my model and dont want anything to be updated on just checking the primary key. Does it takes into consideration all the uniques or do I have to do that manually?

    customer_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      unique: true
    },
    shop_id: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: false,
      unique: true,
      references: {
        model: 'shop',
        key: 'id'
      }
    },
    email: {
      type: DataTypes.STRING(255),
      allowNull: false
    }, 
    others: {
      type: DataTypes.STRING(255),
      allowNull: false
    },{
    timestamps: false,
    createdAt: false,
    updatedAt: false,
    tableName: 'customers'
  }

Upvotes: 3

Views: 6893

Answers (1)

Urvish Kothari
Urvish Kothari

Reputation: 336

As per my view bulkCreate will act only on id (should not consider unique constraints).

So if you trying to insert duplicate values (in column having unique value constraints) using bulkCreate then it will throw an error and will not insert any record. So in such scenario you have to do that check manually.

So what i suggest is to check the unique values first and then go with bulkCreate.

OR

Loop over the records and call findOrCreate method for each record and put unique value columns in where condition like. This will take more time than bulkCreate but more concrete one.

Model.findOrCreate({
where: {
customer_id: cust_val,
shop_id: shop_val
}
}).spread(function(record, created){
if (created){
   console.log('New Record Created');
}
});

Upvotes: 2

Related Questions