How to use fetchNewObject with update.one ReactiveMongo?

不想你离开。 提交于 2021-01-29 05:14:26

问题


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
})

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?

This is my func:

  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)
  }

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


回答1:


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

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 ...

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

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



来源:https://stackoverflow.com/questions/62812419/how-to-use-fetchnewobject-with-update-one-reactivemongo

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