ReactiveMongo:如何将列表反序列化为Option [英] ReactiveMongo: How to deserialize a list into an Option

查看:141
本文介绍了ReactiveMongo:如何将列表反序列化为Option的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个代表用户的case类,其伴随对象提供了BSONDocumentWriterBSONDocumentReader以便对BSON进行序列化/反序列化:

Here below is a case class that represents an user, and its companion object provides a BSONDocumentWriter and BSONDocumentReader to serialize/deserialize to/from BSON:

case class User(
  id: Option[BSONObjectID],
  name: String,
  addresses: Option[List[BSONObjectID]]
)

object User {
  implicit object UserWriter extends BSONDocumentWriter[User] {
    def write(user: User) = BSONDocument(
      "_id" -> user.id.getOrElse(BSONObjectID.generate),
      "name" -> user.name,
      "addresses" -> user.addresses
    ) 
  }

  implicit object UserReader extends BSONDocumentReader[User] {
    def read(doc: BSONDocument) = User(
      doc.getAs[BSONObjectID]("_id"),
      doc.getAs[String]("name").get,
      doc.getAs[List[BSONObjectID]]("addresses").toList.flatten,
    )
  }
}

上面的代码无法编译,因为User.addressesOption,并且我总是收到以下错误:

The code above does not compile because User.addresses is an Option and I always get the following error:

/home/j3d/Projects/test/app/models/User.scala:82: polymorphic expression cannot be instantiated to expected type;
[error]  found   : [B]List[B]
[error]  required: Option[List[reactivemongo.bson.BSONObjectID]]
[error]       doc.getAs[List[BSONObjectID]]("addresses").toList.flatten,
                                                                ^

如果输入的BSON包含addresses,如何将其反序列化为Option[List[BSONObjectID]]?

If the input BSON contains addresses, how do I deserialize it into an Option[List[BSONObjectID]]?

推荐答案

为什么要先调用toList,然后再调用flatten?如果我正确地阅读了BSONDocument的文档,则getAs方法将为类型T返回Option,在这种情况下,您将T指定为List[BSONObjectID].调用toList时,基本上是将Option拆包为空的List(对于None)或对于实际的List.然后,这里的flatten似乎没有做任何相关的事情.您不能只按以下方式操作吗?

Why are you calling toList and then flatten? If I'm reading the docs correctly for BSONDocument, the getAs method will return an Option for type T where in your case, you are specifying T as List[BSONObjectID]. When you call toList, you are basically unpacking the Option to either an empty List (in the case of a None) or into the actual List in the case of a Some. And then the flatten here doesn't seem to be doing anything relevant. Can't you just do it as:

doc.getAs[List[BSONObjectID]]("addresses")

这篇关于ReactiveMongo:如何将列表反序列化为Option的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆