ReactiveMongo/Play-ReactiveMongo

Include the ID inside case class

mhriemers opened this issue · 3 comments

I'm trying to write a CRUD style application using this and Play. My case classes look like this:

case class Resume(
                 _id: Option[String],
                 name: String,
                 location: String,
                 additional: String,
                 experience: List[Experience],
                 education: List[Education]
                   )

case class Experience(
                     role: String,
                     period: String,
                     employer: String,
                     responsibilities: String,
                     skillsUsed: String
                       )

case class Education(
                    title: String,
                    institution: String,
                    period: String
                      )

How do I assign _id to the Mongo DB id?

I've used the dirtiest trick in the book and created my own Reads and Writes for the Resume case class.

val resumeReads: Reads[Resume] = (
      (JsPath \ "_id" \ "$oid").read[Option[String]] and
      (JsPath \ "name").read[String] and
      (JsPath \ "location").read[String] and
      (JsPath \ "additional").read[String] and
      (JsPath \ "experience").read[List[Experience]] and
      (JsPath \ "education").read[List[Education]]
    )(Resume.apply _)

  val resumeWrites: Writes[Resume] = (
      (JsPath \ "_id" \ "$oid").write[Option[String]] and
      (JsPath \ "name").write[String] and
      (JsPath \ "location").write[String] and
      (JsPath \ "additional").write[String] and
      (JsPath \ "experience").write[List[Experience]] and
      (JsPath \ "education").write[List[Education]]
    )(unlift(Resume.unapply))

  implicit val resumeFormat = Format(resumeReads, resumeWrites)

If there is a better solution (must be), please do tell me so! For peeps running into the same struggles, this works :)

Hi @ipsq , it would better better to go to the Google Group to discuss of various possible ways (rather than there in the issue tracker). Thanks.

Since the discussion is moved in the Google Group, this can be closed.