ReactiveMongo BSONHandler for Map

时间:2016-05-12 09:26:08

标签: scala reactivemongo

我有以下课程,并希望使用reactivemongo.bson.Macros.handler自动获取读者和作者。

case class Data(a: String, b: Map[String, String])
object Data {
  implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}

但它无法编译,说Implicit Map[String,String] for 'value vs' not found

如何使这项工作?我正在使用reactivemongo_2.10 0.11.10

1 个答案:

答案 0 :(得分:2)

根据this gist,我找到了一个解决方案:

case class Data(date: String, base: String, vs: Map[String, String])

object Data {
  implicit object BSONMapHandler extends BSONHandler[BSONDocument, Map[String, String]] {
    override def read(bson: BSONDocument): Map[String, String] = {
      bson.elements.map {
        case (key, value) => key -> value.asInstanceOf[BSONString].value
      }.toMap
    }

    override def write(t: Map[String, String]): BSONDocument = {
      val stream: Stream[Try[(String, BSONString)]] = t.map {
        case (key, value) => Try((key, BSONString(value)))
      }.toStream
      BSONDocument(stream)
    }
  }
  implicit val dataHandler = reactivemongo.bson.Macros.handler[Data]
}

不知道为什么reactivemongo默认不支持它。