ReactiveMongo:如何将列表反序列化为选项

时间:2014-01-01 17:20:59

标签: json mongodb scala reactivemongo

下面是一个代表用户的案例类,其配套对象提供BSONDocumentWriterBSONDocumentReader来序列化/反序列化到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而且我总是收到以下错误:

/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]]

1 个答案:

答案 0 :(得分:1)

为什么要拨打toList然后flatten?如果我正在为BSONDocument正确阅读文档,则getAs方法将为类型Option返回T,在您的情况下,您指定{{1}作为T。当您致电List[BSONObjectID]时,您基本上将toList解包为空的Option(如果是List)或实际的None List的情况。然后Some似乎没有做任何相关的事情。你不能这样做:

flatten