我正在使用Play Framework和ReactiveMongo开发应用程序。
我想为类型为Seq[Entities]
这是我的模特:
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]
}
问题是:
1)如何使用表单发布Certificate
实体?
因为当我使用时:
def createCertificate(email: String, certificate: Certificate) = {
val createCertificate = Json.obj(
"$set" -> Json.obj(
"education.certificates" -> certificate
)
)
collection.update(
Json.obj("email" -> email),
createCertificate
)
}
它创建对象数组[...},对象数组[...},...]
2)如何通过ID从Seq中删除Certificate
实体?
由于
答案 0 :(得分:1)
1)我假设您希望createCertificate
将单个证书添加到(可能为空)证书数组,而不是使用单个证书创建数组。在这种情况下,您可以使用$set
运算符替换$push
运算符:
val createCertificate = Json.obj(
"$push" -> Json.obj(
"education.certificates" -> certificate
)
)
2)同样,要删除元素,您可以使用$pull
运算符:
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
)
}