Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of inserted row from upsert (insertOrUpdate) Sequelize Node.js

I'm creating a REST API. I would like to implement an indepotent PUT operation, that either creates or updates the specific resource in database.

I'm using node.js, postgreSQL and sequelize. The problem is that sequelize upsert returns either true or false depending on wheter the resource got updated or created.

But I need to be able to send unique identifier (column id) back to the client, if the resource got created.

One solution that I tried was trying to find the exact same resource by specifing every single column send from client in "where" property of sequelize findOne query. But it throws errors, if client send additional columns that are not in database. And this shouldn't be the case in my implementation.

Is it possible to implement this? Optimally without some performance overhead. Thanks

like image 725
Matúš Čongrády Avatar asked Jun 09 '16 15:06

Matúš Čongrády


1 Answers

Getting the ID back from upsert in Sequelize is not possible at the moment. For more information see: https://github.com/sequelize/sequelize/issues/3354

A possible solution to this issue is to force the user (or the REST API client in this case) to supply the ID of a record in case update is requested, and to not supply an ID in case of creating a new record. This is generally a good idea as it prevents a round trip to the DB, though it makes your API a bit more strict.

like image 162
Gilad Artzi Avatar answered Sep 17 '22 21:09

Gilad Artzi