How to insert JSON documents in Mongodb using Play/Scala ?

176 views
Skip to first unread message

Aravind M

unread,
Mar 8, 2016, 3:45:25 AM3/8/16
to ReactiveMongo - http://reactivemongo.org
Hi all, I am trying to upload/insert json object/document from my front-end to store in Reactivemongo database(2.6) using Play/Scala framework(2.2.3). I have done the following trails, but I am failing to insert json document in the database. 

class Application extends Controller with MongoController {
def jsinfocollection: JSONCollection = db.collection[JSONCollection]("mycollection")
def createJson = Action.async(parse.json) {
    request =>
        request.body.validate[JsValue].map {
println("calling: request.body.validate..!!")//coming message on Play console
        jsoninfo =>
          jsinfocollection.insert(jsoninfo).map {
  println("calling: jsinfocollection.insert..!!")//coming message on Play console
            lastError =>//Error is showing on Play console: play - Cannot invoke the action, eventually got an error: play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(errir.expected.jsobject,WrappedArray())))))]]
              logger.debug("Json data inserted Successfully in Mongodb collection with LastError: $lastError")
              Created("JsonInfo is Saved")
          }
      }.getOrElse(Future.successful(BadRequest("invalid json data")))
  }
}

I created a collection,called: "mycollection" in Mongodb already like: >db.createCollection("mycollection")
{ "ok" : 1 }

but if I give: >db.mycollection.count() - is giving 0, otherwise if I give: db.mycollection.find() - is giving nothing

routes:
POST /createJson controllers.Application.createJson

Error:
POST http://localhost:9000/createJson 500 (Internal Server Error)
play - Cannot invoke the action, eventually got an error: play.api.libs.json.JsResultException: JsResultException(errors:List((,List(ValidationError(errir.expected.jsobject,WrappedArray())))))]]

Please help me regarding this where and what I am doing wrong to upload/insert my json data into my required collection("mycollection") ?

Cédric Chantepie

unread,
Mar 8, 2016, 7:24:26 AM3/8/16
to ReactiveMongo - http://reactivemongo.org
I guess the question has already been posted on StackOverflow (BTW please avoid duplicate questions).

As said, you would get more support using recent versions, Play 2.2 is quite old.

Aravind M

unread,
Mar 9, 2016, 4:10:42 AM3/9/16
to ReactiveMongo - http://reactivemongo.org

Hi Cédric Chantepie, 
yes, but my application requires 2.2.3 version only. May I know anything where I am doing wrong ?

Reply all
Reply to author
Forward
0 new messages