下面是一个代表用户的案例类,其配套对象提供BSONDocumentWriter
和BSONDocumentReader
来序列化/反序列化到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.addresses
是Option
而且我总是收到以下错误:
/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]]
?
答案 0 :(得分:1)
为什么要拨打toList
然后flatten
?如果我正在为BSONDocument
正确阅读文档,则getAs
方法将为类型Option
返回T
,在您的情况下,您指定{{1}作为T
。当您致电List[BSONObjectID]
时,您基本上将toList
解包为空的Option
(如果是List
)或实际的None
List
的情况。然后Some
似乎没有做任何相关的事情。你不能这样做:
flatten