【发布时间】:2015-02-13 16:13:59
【问题描述】:
我定义了BSONDocumentWriters 以使用 ReactiveMongo 驱动程序将域对象(案例类)映射到要在 MongoDB 中持久化的 BSON 文档。对于案例类来说,定义作者是非常直接的(虽然乏味且容易出错:我希望有一个类似 Salat 的解决方案)。但是,我似乎无法为Map[String,Any] 做同样的事情(其中的值可以是数字、日期或字符串类型)。我找到了一个code example,它为地图定义了一个通用的写入器(和读取器):
implicit def MapWriter[V](implicit vw: BSONDocumentWriter[V]): BSONDocumentWriter[Map[String, V]] =
new BSONDocumentWriter[Map[String, V]] {
def write(map: Map[String, V]): BSONDocument = {
val elements = map.toStream.map { tuple =>
tuple._1 -> vw.write(tuple._2)
}
BSONDocument(elements)
}
}
但是如果V 类型没有隐含的BSONDocumentWriter,则这不起作用,即sn-p:
BSONDocument(
"_id" -> "asd",
"map" -> MapWriter[Any].write(Map("x" -> 1, "y" -> "2"))
)
无法编译:
could not find implicit value for parameter vw: reactivemongo.bson.BSONDocumentWriter[Any]
"map" -> MapWriter[Any].write(Map("x" -> 1, "y" -> "2"))
^
我想也许作者应该写信给BSONValue而不是BSONDocument,所以我将示例修改如下:
implicit def ValueMapWriter[V](implicit vw: BSONWriter[V, BSONValue]): BSONDocumentWriter[Map[String, V]] =
new BSONDocumentWriter[Map[String, V]] {
def write(map: Map[String, V]): BSONDocument = {
val elements = map.toStream.map {
tuple =>
tuple._1 -> vw.write(tuple._2)
}
BSONDocument(elements)
}
}
为了简单起见,我尝试使用 Int 作为值类型,但同样是 sn-p:
BSONDocument(
"_id" -> "asd",
"map" -> ValueMapWriter[Int].write(Map("x" -> 1, "y" -> 2))
)
无法编译:
could not find implicit value for parameter vw: reactivemongo.bson.BSONWriter[Int,reactivemongo.bson.BSONValue]
"map" -> ValueMapWriter[Int].write(Map("x" -> 1, "y" -> 2))
^
如果上述方法可行,我可以使用一些基类作为值类型并定义其隐式编写器。
我不确定为什么会发生这种情况以及如何解决它。也许我错过了一些明显的东西?想法?
【问题讨论】:
标签: mongodb scala reactivemongo