1

在我当前的 Play2 项目中,我实现了 ReactiveMongo 来存储我的用户对象。

用户:

case class User(override var _id: Option[BSONObjectID] = None,
                override var created: Option[DateTime] = None,
                override var updated: Option[DateTime] = None,
                firstName: String,
                lastName: String,
                email: String,
                emailValidated: Boolean,
                phoneNumber: String,
                lastLogin: DateTime,
                linkedProviders: Seq[LinkedProvider],
                userRoles: Seq[UserRole.UserRole]) extends TemporalModel {
}

import EnumUtils.enumReads
implicit val userRoleReads = enumReads(UserRole)
import mongo_models.LinkedProvider.linkedProviderReads
implicit val userReads: Reads[User] = (
    (__ \ "_id").read[Option[BSONObjectID]] and
      (__ \ "created").read[Option[DateTime]] and
      (__ \ "updated").read[Option[DateTime]] and
      (__ \ "firstName").read[String] and
      (__ \ "lastName").read[String] and
      (__ \ "email").read[String] and
      (__ \ "emailValidated").read[Boolean] and
      (__ \ "phoneNumber").read[String] and
      (__ \ "lastLogin").read[DateTime] and
      (__ \ "linkedProviders").read(list[LinkedProvider](linkedProviderReads)) and
      (__ \ "userRoles").read(list[UserRole.UserRole])
    )(User.apply _)


  import EnumUtils.enumWrites
  import mongo_models.LinkedProvider.linkedProviderWrites
  import play.api.libs.json.Writes._

  implicit val userWrites: Writes[User] = (
    (__ \ "_id").write[Option[BSONObjectID]] and
      (__ \ "created").write[Option[DateTime]] and
      (__ \ "updated").write[Option[DateTime]] and
      (__ \ "firstName").write[String] and
      (__ \ "lastName").write[String] and
      (__ \ "email").write[String] and
      (__ \ "emailValidated").write[Boolean] and
      (__ \ "phoneNumber").write[String] and
      (__ \ "lastLogin").write[DateTime] and
      (__ \ "linkedProviders").write(Writes.traversableWrites[LinkedProvider](linkedProviderWrites)) and
      (__ \ "userRoles").write(Writes.traversableWrites[UserRole.UserRole])
    )(unlift(User.unapply))

链接提供者:

case class LinkedProvider(userId: String,
                          providerId: String,
                          authMethod: String,
                          avatarUrl: String,
                          oAuth1Info: Option[OAuth1Info] = None,
                          oAuth2Info: Option[OAuth2Info] = None,
                          passwordInfo: Option[PasswordInfo] = None) {

}

object LinkedProvider {

  implicit val o1 = Json.format[OAuth1Info]
  implicit val o2 = Json.format[OAuth2Info]
  implicit val p = Json.format[PasswordInfo]

  implicit val linkedProviderReads: Reads[LinkedProvider] = (
    (__ \ "userId").read[String] and
      (__ \ "providerId").read[String] and
      (__ \ "authMethod").read[String] and
      (__ \ "avatarUrl").read[String] and
        (__ \ "oAuth1Info").read[Option[OAuth1Info]] and
        (__ \ "oAuth2Info").read[Option[OAuth2Info]] and
          (__ \ "passwordInfo").read[Option[PasswordInfo]]
    )(LinkedProvider.apply _)

  implicit val linkedProviderWrites: Writes[LinkedProvider] = (
    (__ \ "userId").write[String] and
      (__ \ "providerId").write[String] and
      (__ \ "authMethod").write[String] and
      (__ \ "avatarUrl").write[String] and
      (__ \ "oAuth1Info").write[Option[OAuth1Info]] and
      (__ \ "oAuth2Info").write[Option[OAuth2Info]] and
      (__ \ "passwordInfo").write[Option[PasswordInfo]]
    )(unlift(LinkedProvider.unapply))
}

如您所见,我已经实现了读取和写入,以便将对象正确存储在 mongoDB 实例中。使用新对象进行插入时,一切都像魅力一样工作,并且对象结构已正确保存并从 mongoDB 检索。

我遇到的问题是弄清楚如何处理更新。所以假设我想像这样更新我的用户对象上的一些值:

val userForUpdate = user.copy(
       firstName = identity.firstName,
       lastName = identity.lastName,
       email = identity.email.getOrElse(""),
       lastLogin = DateTime.now()
       )

然后调用我的更新方法:

UserDAO.update(user._id.get.stringify, userForUpdate, false)

更新方法:

def update(id: String, document: T, upsert: Boolean)(implicit writer: Writes[T]): Future[Either[ServiceException, T]] = {
    document.updated = Some(new DateTime())
    Logger.debug(s"Updating document: [collection=$collectionName, id=$id, document=$document]")
    Recover(collection.update(DBQueryBuilder.id(id), DBQueryBuilder.set(document))) {
      document
    }
  }

DBQueryBuilder.set() 方法:

def set[T](data: T)(implicit writer: Writes[T]): JsObject = Json.obj("$set" -> data)

这将导致此错误:

[error] application - DB operation failed: [message=DatabaseException['Mod on _id not allowed' (code = 10148)]]
[error] application - DatabaseException: [code=10148, isNotAPrimaryError=false]

由于写入说明,在调用DBQueryBuilder.set() 方法(__ \ "_id").write[Option[BSONObjectID]]时也应该序列化_id字段。我们知道更新_id是不允许的,在这种情况下绝对不应该这样做。

所以我的问题是:我应该如何处理这个?我想有一些聪明的 Scala 方式不涉及我编写整个"$set" -> 查询?也许创建一个更好的 DBQueryBuilder?也许定义另一个写入定义?
请给你最好的机会,记住我是一个 Scala 新手,所以要温柔 =) !

4

2 回答 2

0

代替

def set[T](data: T)(implicit writer: Writes[T]): JsObject = Json.obj("$set" -> data)

你可以使用类似的东西

def set[T](data: T)(implicit writer: Writes[T]): JsObject = {
    val data = Json.obj(data)
    val dataWithoutId = data.remove("_id")
    Json.obj("$set" -> dataWithoutId)
}

Play Json 库中应该有一些东西可以删除该_id字段(但它可能不是“remove(...)”...)


由于您使用选项,您可能会编写如下内容:

val userForUpdate = user.copy(
       id = None,
       firstName = identity.firstName,
       lastName = identity.lastName,
       email = identity.email.getOrElse(""),
       lastLogin = DateTime.now()
       )

最好的方法可能是对所有代表 Mongo 文档的类使用一个共同的特征(也许你使用的 T?),并在特征上添加删除 id 的可能性(将其设置为无)。

这样你可以调用:

def set[T](data: T)(implicit writer: Writes[T]): JsObject = Json.obj("$set" -> data.copy(_id = None))
于 2013-08-16T08:28:42.137 回答
0

这个怎么样?

def set[T](data: T)(implicit writer: Writes[T]): JsObject = {
    val jsonTransformer = (__ \ '$set \ '_id).json.prune
    val dataWithId = Json.obj("$set" -> data)
    val withoutId = dataWithId.transform(jsonTransformer).get
    withoutId
}
于 2013-08-16T09:16:17.887 回答