鉴于以下文件
{:xt/id 1
:line-item/quantity 23
:line-item/item 20
:line-item/description "Item line description"}
Run Code Online (Sandbox Code Playgroud)
我想将数量更新为25
据我所知,到目前为止,我需要首先查询数据库,获取完整的文档,合并更改,然后将新文档处理回来。
有没有办法只合并数量上的变化而不执行上述操作?
谢谢
小智 7
您应该能够为此使用事务功能。这些将允许您指定这些多个步骤并将它们推送到事务日志中,以确保它们按顺序执行(即您将始终检索最新的文档以在推送事务函数调用本身的时间点进行更新)到事务日志中)。
对于您的具体示例,我认为它看起来像这样(未经测试):
(xt/submit-tx node [[::xt/put
{:xt/id :update-quantity
;; note that the function body is quoted.
;; and function calls are fully qualified
:xt/fn '(fn [ctx eid new-quantity]
(let [db (xtdb.api/db ctx)
entity (xtdb.api/entity db eid)]
[[::xt/put (assoc entity :line-item/quantity new-quantity)]]))}]])
Run Code Online (Sandbox Code Playgroud)
这会创建交易函数本身,然后您只需调用它即可进行更改:
;; `[[::xt/fn <id-of-fn> <id-of-entity> <new-quantity>]]` -- the `ctx` is automatically-injected
(xt/submit-tx node [[::xt/fn :update-quantity 1 25]])
Run Code Online (Sandbox Code Playgroud)