【问题标题】:Reactivemongo serializing a map into a BSONDocumentReactivemongo 将地图序列化为 BSONDocument
【发布时间】: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


    【解决方案1】:

    ValueMapWriter 定义中BSONValue 的泛型类型参数边界不正确。如果换行

    implicit def ValueMapWriter[V](implicit vw: BSONWriter[V, BSONValue]): BSONDocumentWriter[Map[String, V]] =
    

    implicit def ValueMapWriter[V](implicit vw: BSONWriter[V, _ <: BSONValue]): BSONDocumentWriter[Map[String, V]] =
    

    那么它应该解析 Int 的隐式写入器。

    顺便说一句simple-reactivemongo 已经这样做了。而且我还打算将此功能添加到ReactiveMongo Extensions

    【讨论】:

    • 没有测试它,因为不幸的是我不再使用 Scala 但它是有道理的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2020-06-26
    相关资源
    最近更新 更多