使用Reactivemongo,Play框架和Scala插入嵌套文档

时间:2015-04-02 12:01:03

标签: mongodb scala playframework-2.3 reactivemongo play-reactivemongo

我是使用scala和reactivemongo玩Play framework 2.3的新手。我已经开发了几个页面来将表格中的数据加载到mongodb中。

到目前为止一切顺利。但是现在我打算使用mongodb的嵌套文档功能,因为在mongodb中没有直接支持JOINS。我知道手动引用和DB引用方式加入MongoDB中的集合。

此论坛上发布了一些与mongodb中嵌套文档相关的问题,但它们对我毫无帮助。

如果您能使用play framework,scala和reactivemongo向我展示如何插入更新子文档在mongodb集合中已有的文档中,我将不胜感激?

数据结构如下:

   "_id" : ObjectId("5516ae699aaebdfc0bc47f7d"),
   "name" : "ABCD",
   "address" : "Blue Skies",
   "dob" : 135962900000,
   "email" : ""

我想添加新的子文档条目如下:

   "_id" : ObjectId("5516ae699aaebdfc0bc47f7d"),
   "name" : "ABCD",
   "address" : "Blue Skies",
   "dob" : 01/01/1970,
   "email" : "",
      “visits” : [
    { 
        “date” : 18/02/2015,
        “comments” : “Some comments”,
        “createdBy” : “XYZ”
    },
    { 
        “date” : 23/03/2015,
        “comments” : “Some comments”,
        “createdBy” : “PQR” 
      }
     ]

以下是我在集合中更新文档的代码如下所示:

def updateData(id: String) = Action.async { implicit request =>
projectForm.bindFromRequest.fold(
  formWithErrors => Future.successful(BadRequest(html.editProject(id, formWithErrors))),
  project => {
    val futureUpdateProj = collection.update(Json.obj("_id" -> Json.obj("$oid" -> id)), project.copy(_id = BSONObjectID(id)))
    futureUpdateProj.map { result =>
      projectsHome.flashing("success" -> s"Project ${project.name} has been updated")
    }.recover {
      case t: TimeoutException =>
        Logger.error("Problem found in Project update process")
        InternalServerError(t.getMessage)
    }
  })
  }

0 个答案:

没有答案
相关问题