I am new to Play framework 2.3 using scala and reactivemongo. I have already developed few pages to load data from forms into mongodb.
So far so good. But now I’m planning to use nested document feature of mongodb as there is no direct support for JOINS in mongodb. I am aware of manual reference and DB refs way joining collections in MongoDB.
There are some questions posted on this forum related to nested documents in mongodb but they are of no help to me.
I would really appreciate if you can show me, how to insert and update sub-documents in the already existing document in mongodb collection using play framework, scala and reactivemongo?
The structure of the data is as follows:
"_id" : ObjectId("5516ae699aaebdfc0bc47f7d"),
"name" : "ABCD",
"address" : "Blue Skies",
"dob" : 135962900000,
"email" : ""
And I would like to add new sub-document entries as follows:
"_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”
}
]
Here’s how my code for updating a document in a collection looks like:
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)
}
})
}