如何将 fetchNewObject 与 update.one ReactiveMongo 一起使用? [英] How to use fetchNewObject with update.one ReactiveMongo?

查看:53
本文介绍了如何将 fetchNewObject 与 update.one ReactiveMongo 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前我使用 findAndUpdate 并且可以添加 fetchNewObject = true 所以我可以在查询之后做这样的事情:

Previously I used findAndUpdate and could add fetchNewObject = true so I was able to do something like this after the query:

.map(_.result[WhicherReport].getOrElse {
  throw new NoSuchElementException
})

但是我现在正在使用事务并且只能执行 update.one(...) 并且没有选项可以传递它 fetchNewObject,我该怎么办?

but I'm using transaction now and could only perform update.one(...) and there is no option to pass it fetchNewObject, what can I do?

这是我的功能:

  def someUpdateFunc(collection: BSONCollection, metadata: Metadata, ids: List[String]): Future[UpdateWriteResult] = {
    collection.update.one(
      q = Json.obj("metadata" -> metadata,
        notLocked(now)),
      u =  Json.obj("$set" -> Json.obj("expenses.$[elem].paired" -> true)),
      upsert = false,
      multi = false,
      arrayFilters = Seq(BSONDocument("elem.id" -> BSONDocument( "$in" -> ids))),
      collation = None)
  }

并且我想使用 ReactiveMongo 返回新的更新案例类.

and I want to return the new updated case class using ReactiveMongo.

推荐答案

没有办法将 fetchNewObjectupdate command,因为它不是此命令支持的选项.

There is no way to use fetchNewObject with an update command, as it's not an option supported by this command.

您似乎认为 findAndModify 不能用于事务,但事实并非如此:它可以与事务一起使用.

You seems to think that findAndModify cannot be used with transaction, which not the case: it can be used with transaction.

for {
  ds <- db.startSession()
  dt <- ds.startTransaction(None)

  coll = dt.collection(colName)
  _ <- coll.findAndUpdate(selector, james, upsert = true)
} yield ...

如果您出于未提及的原因仍想使用update,则需要在同一事务中之后执行find.

If you still want to use update for unmentioned reason, then you will need to execute a find after, in the same transaction.

附言.getOrElse { throw new NoSuchElementException } 是一种代码异味,应该劝阻(而是撰写).

P.S. .getOrElse { throw new NoSuchElementException } is quite a code smell, which should be discouraged (and rather compose).

这篇关于如何将 fetchNewObject 与 update.one ReactiveMongo 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆