将以前的answer用于ReactiveMongo 0.12.0("org.reactivemongo" %% "play2-reactivemongo" % "0.12.0"
)和Play 2.5.10。
代码完美地更新了MongoDB文档,但从不返回数据库中的值。尝试了各种方法,但findAndUpdate
永远不会返回值。感谢任何帮助。
@Singleton
//class Counters extends Controller with MongoController {
class Counters @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def collection: JSONCollection = db.collection[JSONCollection]("counters")
def collectionBSON: BSONCollection = db.collection[BSONCollection]("counters")
def incrementCounter(name: String):Future[Option[Long]] = {
import reactivemongo.api.collections.bson.BSONBatchCommands.FindAndModifyCommand.FindAndModifyResult
implicit val reader = Macros.reader[Counter]
val resultFut: Future[FindAndModifyResult] = collectionBSON.findAndUpdate(
BSONDocument("name" -> COUNTER_NAME),
BSONDocument("$inc" -> BSONDocument("seq" -> 5)),
fetchNewObject = true,
upsert = true
)
//resultFut.map(_.result[Counter])
val updatedCountOpt = resultFut.map { r =>
r.result[Counter].map { p =>
println("=====inside Counters.scala p.seq=" + p.seq)
p.seq
}
}
updatedCountOpt
}