scala - 如何使用 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"
}
如何获取插入数据库的完整对象?
解决方案
推荐阅读
- python - 如何在 Python 中解析带有括号的电子邮件 FROM 标头?
- ios - 如何将表格视图的刷新控制作为常用功能实现
- python - 将条带应用于 DataFrame 中的列表列
- r - 按 y 轴上的位置顺序连接 ggplot 中的点
- excel - 将相同的格式应用于具有不同输入的不同单元格
- javascript - 在 iframe 表单中传递数据并使用 Google Analytics(分析)对其进行跟踪
- c++ - 如何在两个类之间发送/接收消息
- ios - iOS:应用程序扩展如何将文件复制到应用程序 Documents/ 文件夹?
- c# - 为什么没有任何东西传递给 .UseStartup
() 默认 webapi .Net Core 应用程序中的方法? - html-framework-7 - Framework7 没有从 DOM 中的外部链接插入加载的内容