首页 > 解决方案 > 如何使用 ReactiveMongo 使用 post API 返回插入 mongo 的完整对象

问题描述

我正在学习 Scala 编程,使用 Play 框架和 ReactiveMongoDB 为我的项目创建 RestAPI 服务。

我正在尝试将一个对象插入到 db,作为 insert 的响应,我想检索使用我在存储库上生成的选项数据创建的对象(例如:Id 是直接从 Mongo 生成的)。

下面的照片显示了我使用的模型。marker_id、_creationDate 和 _updateDate 在存储库中设置。

case class Point_LocationModel(
id: Option[BSONObjectID],
marker_id: Option[String],
step: String,
backgroundTargetName: String,
firstPoint: Option[PointModel],
secondPoint: Option[PointModel],
x: String,
y: String,
z: String,
rotation: String,
note: String,
tag: String,
work_session_id: String,
_creationDate: Option[DateTime],
_updateDate: Option[DateTime] )

这是我用来返回响应数据映射的存储库,但我看到未在响应数据上设置 marker_id、id、_creationDate、_updateDate(第 53 行)。

def create(point: Point_LocationModel)(implicit
      writer: BSONDocumentWriter[Point_LocationModel]
  ) = {
    logger.info(s"output pointInserted point:  ${point}")
    val pointInserted = collection.flatMap(
      _.insert(ordered = false)
        .one(
          point.copy(
            marker_id = Some(BSONObjectID.generate().stringify),
            _creationDate = Some(new DateTime()),
            _updateDate = Some(new DateTime())
          )
        )
        .map((_, point))
    )
    val test1 = Await.result(pointInserted, Duration.Inf)
    logger.info(s"output pointInserted: ${test1}")

    pointInserted
  }

下面是控制器。作为响应,我仅使用传递给 post 调用正文的属性而不是从存储库生成的属性来获取模型。

 def insertPointData(): Action[JsValue] =
    Action.async(controllerComponents.parsers.json) { implicit request =>
      {
        request.body
          .validate[Point_LocationModel]
          .fold(
            _ => Future.successful(BadRequest("Cannot parse request body")),
            point => {
              point_LocationRepository.create(point).map { data =>
                Created(Json.toJson(data._2))
              }
            }
          )
      }
    }

这是完整对象成功插入数据库后,我从控制器的插入方法中得到的最终响应。如图所示,缺少 marker_id 、 id 、 _creationDate 、 _updateDate :

{
    "step": "string11",
    "backgroundTargetName": "string11",
    "firstPoint": {
        "hitPnt": [],
        "normalX": "string1",
        "normalY": "string1",
        "normalZ": "string1"
    },
    "secondPoint": {
        "hitPnt": [],
        "normalX": "string1",
        "normalY": "string1",
        "normalZ": "string1"
    },
    "x": "1",
    "y": "2",
    "z": "3",
    "rotation": "4",
    "note": "test3",
    "tag": "test3",
    "work_session_id": "TEST"
}

如何获取插入数据库的完整对象?

标签: scalareactivemongo

解决方案


推荐阅读