Get the return value of reactivemongo findAndUpdate function

核能气质少年 提交于 2019-12-23 05:07:28

问题


I call the findAndUpdate function on a mongo collection to increase a counter, and I want to get the value of the counter for further use.Here is my code:

collection.findAndUpdate(
    BSONDocument("name" -> "counter"),
    BSONDocument("$inc" -> BSONDocument("count" -> 1)),
    fetchNewObject = true,
    upsert = true
).map{ e =>
    println("count = " + e.value.getAs[Int]("count"))
    //I want to do something with the count here
}

This doesn't compile because e.value.getAs[Int]("count") seems to be wrong. The compile error is:

value getAs is not a member of Option[service.this.collection.BatchCommands.FindAndModifyCommand.pack.Document]

Please kindly advise, thanks!


回答1:


Try this:

case class Person(name: String, count: Int)

object Helpers { 
  def increaseCount(collection: BSONCollection): Future[Option[Int]] = {
    import collection.BatchCommands.FindAndModifyCommand.FindAndModifyResult
    implicit val reader = Macros.reader[Person]

    val resultFut: Future[FindAndModifyResult] = collection.findAndUpdate(
      BSONDocument("name" -> "James"),
      BSONDocument("$inc" -> BSONDocument("count" -> 1)),
      fetchNewObject = true,
      upsert = true
    )

    val updatedCountOpt = resultFut.map { r =>
      r.result[Person].map { p =>
        p.count
      }
    }

    updatedCountOpt
  }
}


来源:https://stackoverflow.com/questions/35548420/get-the-return-value-of-reactivemongo-findandupdate-function

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