0

I'm developing an app with Play Framework and ReactiveMongo. I want to write CRUD operations for a model field with type of Seq[Entities]

Here is my model:

case class Person(_id: Option[BSONObjectID],
                  email: String,
                  password: String,
                  education: Option[Education])

object Lawyer {

  implicit val accountWrites: Writes[Person] = (
    (JsPath \ "_id").writeNullable[BSONObjectID] and
    (JsPath \ "email").write[String] and
    (JsPath \ "password").write[String] and
    (JsPath \ "education").writeNullable[Education]
  )(unlift(Person.unapply))

  implicit val accountReads: Reads[Person] = (
    (JsPath \ "_id").readNullable[BSONObjectID].map(_.getOrElse(BSONObjectID.generate)).map(Some(_)) and
    (JsPath \ "email").read[String] and
    (JsPath \ "password").read[String] and
    (JsPath \ "education").readNullable[Education]
  )(Person.apply _)

case class Education(status: String, certificates: Option[Seq[Certificate]])

object Education {

  implicit val educationFormat: Format[Education] = (
    (JsPath \ "status").format[String] and
    (JsPath \ "certificates").formatNullable[Seq[Certificate]]
  )(Education.apply, unlift(Education.unapply))

}

case class Certificate(id: Option[String] = Some(Random.alphanumeric.take(12).mkString),
                       name: String,
                       licenseCode: Option[String],
                       link: Option[String],
                       date: Date)

object Certificate {

  implicit val certificateFormat = Json.format[Certificate]

}

The questions are:

1) How I can POST the Certificate entity using a form? Because when I use:

def createCertificate(email: String, certificate: Certificate) = {
    val createCertificate = Json.obj(
      "$set" -> Json.obj(
        "education.certificates" -> certificate
      )
    )
    collection.update(
      Json.obj("email" -> email),
      createCertificate
    )
  }

It creates object field {...} insted of array of objects [ {...}, ... ]

2) How I can DELETE the Certificate entity from the Seq by ID?

Thanks

Alex Fruzenshtein
  • 2,846
  • 6
  • 32
  • 53

1 Answers1

1

1) I assume that you want createCertificate to add a single certificate to an (possibly empty) array of certificates instead of creating an array with a single certificate. In that case you can replace your $set operator with the $push operator:

val createCertificate = Json.obj(
  "$push" -> Json.obj(
    "education.certificates" -> certificate
  )
)

2) Likewise, for removing an element you can use the $pull operator:

def removeCertificate(email: String, certificateId: String) = {
  val removeCert = Json.obj(
    "$pull" -> Json.obj(
      "education.certificates" -> Json.obj("id" -> certificateId)
    )
  )
  collection.update(
    Json.obj("email" -> email),
    removeCert
  )
}
edi
  • 3,112
  • 21
  • 16