How to get a result from FindAndModifyResult?

131 views Asked by At

I'm using Play Framework 2.5 and play2-reactivemongo v0.12.4. Trying to create auto-increment counter using findAndUpdate. (I tried using findAndModify. But, I'd no idea how to create one of parameter "commands.JSONFindAndModifyCommand.Modify")

And now I've no idea how to get a result from FindAndModifyResult. I also tried "result[Counter]". But, result seems that doesn't exist..

BaseDAO.scala

class BaseDAO[T] {
  ...
  val collectionName: String
  lazy val collection: Future[JSONCollection] = 
    reactiveMongoApi.database.map(_.collection(collectionName))

  ...
}

CounterDAO.scala

    import play.modules.reactivemongo.json.ImplicitBSONHandlers._
    import play.modules.reactivemongo.ReactiveMongoApi
    import play.api.libs.json._
    import play.api.libs.concurrent.Execution.Implicits._

    trait CounterDAO extends BaseDAO[Counter]

    class CounterDAOImpl @Inject() (val reactiveMongoApi: ReactiveMongoApi)
    extends CounterDAO {
      val collectionName = "counter"

      def incrementCounter(query: JsObject = Json.obj())(implicit writer: OWrites[Counter]): Future[Option[Long]] = {
        // !!        
        collection.map(_.findAndUpdate(query, DBQueryBuilder.inc("seq", 1), fetchNewObject = true)).map(_.value.get)
      }
    }

DBQueryBuilder.scala

object DBQueryBuilder {
  def inc(field: String, amount: Int): JsObject = Json.obj("$inc" -> Json.obj(field -> amount))
}

Counter.scala

case class Counter(
  var _id: Option[BSONObjectID] = None,
  seq: Long
)

[error] shared/src/main/scala/com/xxx/models/daos/CounterDAO.scala:29: type mismatch;
[error]  found   : scala.util.Try[x$3.BatchCommands.FindAndModifyCommand.FindAndModifyResult]
[error]  required: Option[Long]
[error]     collection.map(_.findAndUpdate(query, DBQueryBuilder.inc("seq", 1), fetchNewObject = true)).map(_.value.get)
0

There are 0 answers