16

I'm using Node.js, MySQL and Sequelize. I'd like to insert some 10k rows into a table at once. The table has custom primaryKey field, that is being set manually. The data are downloaded from web and are overlapping.

I'd like to have a version of bulkCreate that wouldn't fail if any of the rows in data have unique keys that are already present in the table. Such kind of things is done in MySQL via INSERT ... ON DUPLICATE KEY UPDATE construct.

How do I do it in Sequelize?

0

4 Answers 4

26

Pass in an options object to bulkCreate with ignoreDuplicates set to true

bulkCreate([...], { ignoreDuplicates: true })
3
  • 4
    This is mysql only unfortunately, does not work on postgres
    – alexbooots
    Apr 5, 2018 at 22:00
  • bulkCreate always insert a single record i am not getting solution . and on second insertion attempt it gives error of unique
    – Nitin
    Apr 16, 2018 at 8:53
  • Soo.. im using v5 and i just spent an hour or so debugging why my bulkCreate was not working. The data you pass into bulkCreate needs to be an array of plain js objects.. not an array of sequelize models. I had a server response.. i was make modifications and using bulkCreate to perform a bulkUpdate.... you need to run row.get({plain:true}) on your data to bring it back down to plain js objects.
    – nawlbergs
    Nov 27, 2019 at 15:52
9

Yuri's answer will ignore duplicates... there is an option for updateOnDuplicate:

Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated.

http://docs.sequelizejs.com/en/latest/api/model/#bulkcreaterecords-options-promisearrayinstance

2

ProductAttribute.bulkCreate(arrayToUpsert, {updateOnDuplicate: ['id', 'attributeValue'] }) - this will update each attributeValue with ids indicated in arrayToUpsert

1

Below is the correct syntax for bulk update, Tested on "sequelize": "6.0.0"

model.bulkCreate(dataToUpdate, { updateOnDuplicate: ["user_id", "token", "created_at"] })

It will update all the columns specfied in updateOnDuplicate by first column values which are in dataToUpdate

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.