问题描述
我正在创建一个REST API。
我想实现一个无能为力的PUT操作,它可以创建或更新数据库中的特定资源。
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.
我正在使用node.js,postgreSQL和sequelize。
问题是sequelize upsert
返回 true
或 false
取决于资源是否已更新或创建。
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.
但我需要能够将唯一标识符(列ID)发送回客户端,如果资源已经创建。
But I need to be able to send unique identifier (column id) back to the client, if the resource got created.
我试过的一个解决方案是通过在sequelize findOne查询的where属性中指定从客户端发送的每一个列来尝试找到完全相同的资源。但是如果客户端发送不在数据库中的其他列,则会抛出错误。在我的实现中不应该这样。
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
推荐答案
从 upsert
获取ID Sequelize目前是不可能的。有关详细信息,请参阅: https://github.com/sequelize/sequelize/issues/3354
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
此问题的一个可能解决方案是强制用户(在这种情况下为REST API客户端)提供记录的ID,以防请求更新,并且在创建新记录时不提供ID。这通常是一个好主意,因为它会阻止往返数据库,但它会使您的API更加严格。
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.
这篇关于从upsert获取插入行的id(insertOrUpdate)Sequelize Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!