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

烈酒焚心 提交于 2019-12-18 16:45:45

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/37730090/get-id-of-inserted-row-from-upsert-insertorupdate-sequelize-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!