【问题标题】:ReactiveMongo: Manage Sequence fieldReactiveMongo:管理序列字段
【发布时间】:2015-01-12 12:35:00
【问题描述】:

我正在使用 Play Framework 和 ReactiveMongo 开发应用程序。 我想为 Seq[Entities] 类型的模型字段编写 CRUD 操作

这是我的模型:

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) 如何从 Seq by ID 中删除 Certificate 实体?

谢谢

【问题讨论】:

    标签: mongodb playframework reactivemongo


    【解决方案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
      )
    }
    

    【讨论】:

    • 谢谢 明天试试 =)
    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2018-01-15
    • 2014-10-23
    相关资源
    最近更新 更多