Search code examples
jsonscalareactivemongo

How to get all data I have Inserted?


I have made a small app using json and reactiveMongo which inserts Students Information.

object Applications extends Controller{

  val studentDao = StudentDaoAndEntity
  val studentqueryReader: Reads[JsObject] = implicitly[Reads[JsObject]]

  def saveStudent = Action.async(parse.json) { request =>
    request.body.validate[StudentInfo].map {
      k => studentDao.insertStudent(k).map {
        l => Ok("Successfully inserted")
      }
    }.getOrElse(Future.successful(BadRequest("Invalid Json"))

In databse

object StudentDaoAndEntity {

  val sreader: Reads[StudentInfo] = Json.reads[StudentInfo]
  val swriter: Writes[StudentInfo] = Json.writes[StudentInfo]
  val studentqueryReader: Reads[JsObject] = implicitly[Reads[JsObject]]

  def db = ReactiveMongoPlugin.db
  def collection: JSONCollection = db[JSONCollection]("student")
  def insertStudent(student: StudentInfo): Future[JsObject]= {   
    val modelToJsObj = swriter.writes(student).as[JsObject]
    collection.insert(modelToJsObj) map (_ => modelToJsObj)
  }

This works fine. Now I need to get all data I have inserted. How can I do that? I am not asking for code but for Idea.


Solution

  • First of all: it seems that you are using Play-ReactiveMongo (as far as i know, JSONCollection is not part of ReactiveMongo itself). If this is the case, then your code is unnecessarily complex. Instead of doing the JSON conversions manually, you just can pass your StudentInfo objects directly to insert. Minimal example:

    val studentInfo: StudentInfo = ...
    def collection: JSONCollection = db[JSONCollection]("student")
    collection.insert(studentInfo) 
    

    That's the elegant part of the Play plugin. Yes, MongoDB persists data as JSON (or BSON, to be more precise), but you don't have do deal with it. Just make sure the implicit Writes (or Reads, in case of querying) is in scope, as well as other necessary imports (e.g. play.modules.reactivemongo.json._).


    Now I need to get all data I have inserted. How can I do that? I am not asking for code but for Idea.

    Well, you want to have a look at the documentation (scroll down for examples), it's quite simple and there is not more to it. In your case, it could look like this:

    // perform query via cursor
    val cursor: Cursor[StudentInfo] =
         collection.find(Json.obj("lastName" -> "Regmi")).cursor[StudentInfo]
    
    // gather results as list
    val futureStudents: Future[List[StudentInfo]] = cursor.collect[List]()
    

    In this case, you get all students with the last name Regmi. If you really want to retrieve all students, then you probably need to pass an empty JsObject as your query. Again, it's not necessary to deal with JSON conversions, as long as the implicit Reads is in scope.