获取 reactivemongo findAndUpdate 函数的 return 值

Get the return value of reactivemongo findAndUpdate function

我在 mongo 集合上调用 findAndUpdate 函数来增加计数器,我想进一步获取计数器的值 use.Here 是我的代码:

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
}

这无法编译,因为 e.value.getAs[Int]("count") 似乎是错误的。 编译错误为:

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

请指教,谢谢!

试试这个:

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