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? });
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.
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.
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.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With