我有一个非常简单的案例类,它是更大案例类的一部分。

case class PublisherStatus(status: String)
case class Publisher(id: Option[BSONObjectID], name: String, status: PublisherStatus, keywords: List[String], updatedAt: Option[DateTime], outputChannelIP: String, outputChannelName: String)


并且我为它定义了BSON读取器和写入器,如下所示。

  implicit object StatusBSONReader extends BSONDocumentReader[PublisherStatus] {
    def read(doc: BSONDocument): PublisherStatus =
      PublisherStatus(
        doc.getAs[String]("status").get
      )
  }

  implicit object StatusBSONWriter extends BSONDocumentWriter[PublisherStatus] {
    def write(status: PublisherStatus): BSONDocument =
      BSONDocument(
        "status" -> status.status)
  }


但是,当我尝试执行以下操作时,出现编译错误。

  def updateState(id: String, s: String) {
    import models.PublisherBSONWriter._
    implicit val statusWrites = Json.writes[PublisherStatus]
    val objectId = new BSONObjectID(id)
    val status = PublisherStatus(s)
    val modifier = BSONDocument("$set" -> status)

    val updateFuture = collection.update(BSONDocument("_id" -> objectId), modifier)

  }


错误-

could not find implicit value for parameter writer: reactivemongo.bson.BSONWriter[models.PublisherStatus, _ <: reactivemongo.bson.BSONValue]
[error]     val modifier = BSONDocument("$set" -> status)
[error]                                        ^
[error] one error found
[error] (compile:compile) Compilation failed

最佳答案

PublisherStatus的读取器和写入器不应是BSONDocumentReaderBSONDocumentWriter,而应该是BSONReaderBSONWriter

为了使事情变得更加简单,请使用BSONHandler。遵循以下原则

implicit val bson = new BSONHandler[BSONString, PublisherStatus] {
  def read(bson: BSONString) = PublisherStatus(bson.value)
  def write(status: PublisherStatus) = BSONString(status.status)
}

关于scala - 在reactmongo中找不到BSON Writer的隐式值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24114037/

10-10 03:47