Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize upsert

i need to get the id for the inserted/updated record when using .upsert() in sequelize.

right now .upsert() returns a boolean indicating whether the row was created or updated.

return db.VenueAddress.upsert({             addressId:address.addressId,             venueId: venue.venueId,             street: address.street,             zipCode: address.zipCode,             venueAddressDeletedAt: null         }).then(function(test){             //test returned here as true or false how can i get the inserted id here so i can insert data in other tables using this new id?         }); 
like image 903
Hussein Al-Far Avatar asked Mar 15 '15 16:03

Hussein Al-Far


People also ask

What is Sequelize upsert?

The upsert() method accepts an object of data with the property keys serving as the column names and the property values as the column values. The method would then return an array of two elements: The instance the Model where you call the method, returning the new/updated row.

What is upsert operation?

The term upsert is a portmanteau – a combination of the words “update” and “insert.” In the context of relational databases, an upsert is a database operation that will update an existing row if a specified value already exists in a table, and insert a new row if the specified value doesn't already exist.

How do I get dataValues from Sequelize?

To get only the dataValues from Sequelize ORM, we can set the raw option to true . Model. findAll({ raw: true, //... }); to call findAll with an object with the raw property set to true to only return the dataValues in the query results.

How do I update multiple rows in Sequelize?

While Sequelize doesn't provide a bulkUpdate() method, both update() and bulkCreate() methods allow you to update multiple rows with a single method. When you need to update multiple rows with different values, you can use the bulkCreate() method.


Video Answer


1 Answers

I don't think that returning the upserted record was available when the OP asked this question, but it has since been implemented with this PR. As of Sequelize v4.32.1, you can pass a boolean returning as a query param to select between returning an array with the record and a boolean, or just a boolean indicating whether or not a new record was created.

You do still need to provide the id of the record you want to upsert or a new record will be created.

For example:

const [record, created] = await Model.upsert(   { id: 1, name: 'foo' }, // Record to upsert   { returning: true }     // Return upserted record ); 
like image 97
Matt Ringer Avatar answered Sep 21 '22 14:09

Matt Ringer