如果我在ReactiveMongo中使用findAndUpdate命令,应该使用什么HTTP请求

时间:2018-08-17 11:15:27

标签: mongodb scala httprequest reactivemongo findandmodify

如果我在ReactiveMongo中使用findAndUpdate命令,应该使用什么 http请求。我的CRUD请求是这样路由的:

GET       /api/1.1/r/:collName                  controllers.admin.MongoC.index(collName: String)
GET       /api/1.1/r/:collName/:id              controllers.admin.MongoC.read(collName: String, id: BSONObjectID)
POST      /api/1.1/c/:collName                  controllers.admin.MongoC.create(collName: String)
PUT       /api/1.1/u/:collName/:id/:many        controllers.admin.MongoC.update(collName: String, id: BSONObjectID, many: Boolean)
DELETE    /api/1.1/d/:collName/:id              controllers.admin.MongoC.delete(collName: String, id: BSONObjectID)

我使用了@cchantep提供的this answer来构造findAndUpdate命令(但采用JSON集合格式-就像我在Play框架中使用JSON插件一样),

MongoRepo.scala

  protected def getCollection(collName: String): Future[JSONCollection] = database.map(_.collection[JSONCollection](collName))

  def findAndUpdate(collName: String)(selector: JsObject, update: JsObject, oProjection: Option[JsObject]): Future[Option[JsObject]] = {

    getCollection(collName).flatMap(
      _.findAndUpdate(selector, Json.obj("$set" -> update), fetchNewObject = true, upsert = true, fields = oProjection)
        .map(_.result[JsObject])
    )

  }

控制器如下所示:

MongoC.scala

   def getQueryParameterJSV(param: String) = { implicit request: Request[JsValue] =>

       val oQueryStr = request.getQueryString(param)

       oQueryStr match {
           case Some(_) => Json.parse(oQueryStr.get).asInstanceOf[JsObject]
           case None => Json.obj()
       }

   }

   def findAndUpdate(collName: String, id: BSONObjectID) = Action.async(parse.json) { implicit request: Request[JsValue] =>

       val q = getQueryParameterJSV("q")(request)
       val p = getQueryParameterJSV("p")(request)
       val doc = request.body.as[JsObject]

       mongoRepo.findAndUpdate(collName)(q, doc, Some(p)).map(widget => Ok(Json.toJson(widget)))

   }

路线:

管理路由

PUT      /api/1.1/ur/:collName/:id        controllers.admin.MongoC.findAndUpdate(collName: String, id: BSONObjectID)

我正在使用邮递员进行测试,当我查询此URL时,我得到了应有的外观的更新文档,但是查询集合后,我看到它仍然包含旧值。我的其他CRUD命令正常运行任何帮助/知识都将非常有用。谢谢

0 个答案:

没有答案