polkovnikov.ph
polkovnikov.ph

Reputation: 6632

Sequelize: insert in bulk

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?

Upvotes: 16

Views: 32735

Answers (4)

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

Upvotes: 2

Rohit Parte
Rohit Parte

Reputation: 4076

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

Upvotes: 1

Sean
Sean

Reputation: 300

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

Upvotes: 9

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

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

bulkCreate([...], { ignoreDuplicates: true })

Upvotes: 26

Related Questions