执行2次操作以在ReactiveMongo上更新

时间:2016-04-08 00:35:35

标签: mongodb scala reactivemongo play-reactivemongo

我正在测试mongo shell上的下一个2查询是否有效,

但现在,我需要在reactivemongo中执行相同的查询

有人可以就如何在reactivemongo中进行查询提出建议

doc = db.offer.find({"_id": "5704441ea356f55ab590e8f4"})

db.student.update(
  { "_id" : "570681b30fc032dea831c132"},
  { $push: { 
    "presell": [
        { "_id" : doc }
      ]
    } 
  }
)

有更好的方法来运行此查询吗?

1 个答案:

答案 0 :(得分:0)

使用flatMap是我正在寻找的解决方案

  def preSell( user_id: String, offer_id: String ) = Action.async {

    val futureResults = collection_offer.find( Json.obj("_id" -> offer_id ) ).one[JsValue]
    futureResults.flatMap {
      case Some(document) => 

        val futureUpdate = collection.update( Json.obj( "_id" -> user_id ), Json.obj( "$addToSet" -> Json.obj( "presell" ->  Json.toJson(document) ) ) )

        futureUpdate.map { result =>
          Logger.debug("Successfully update")
          Ok( Json.obj( data -> Json.obj( "_id" -> user_id ) ) )
        }.recover {
          case t: TimeoutException =>
            Logger.error("Problem found in student update process")
            InternalServerError(t.getMessage)
        }

      case None => 
        Future.successful( Ok( Json.obj( data -> "Document NotFound" ) ) )
    }.recover {
      case t: TimeoutException =>
        Logger.error("Problem obtaining teacher")
        InternalServerError(t.getMessage)
    }

  }

Scala Play Action.async cant resolve Ok as mvc.AnyContent