问题
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