3

下面再次是我在一篇文章中介绍的案例类......但使用cmbaxter建议的修复:

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")
    )
  }
}

现在我正在尝试实现一个 Play 控制器来验证传入的 Json 并将其保存到数据库(MongoDB)中。下面是我的代码:

object Users extends Controller with MongoController {

  private def collection = db.collection[JSONCollection]("users")

  def create = Action.async(parse.json) { request =>
    request.body.validate[User].map { user =>
      collection.insert(user).map { lastError =>
        Logger.debug(s"Successfully inserted with LastError: $lastError")
        Created
      }
    }.getOrElse(Future.successful(BadRequest("invalid json")))
  }
}

上面的代码无法编译,因为编译器没有找到任何 Json 反序列化器:

[error] /home/j3d/Projects/test/app/controllers/Users.scala:44: No Json deserializer found for type models.User. Try to implement an implicit Reads or Format for this type.
[error]     request.body.validate[User].map { user =>
[error]                          ^

是否可以重用我在伴随对象中定义的BSONDocumentWriterand而不是实现and ?BSONDocumentReaderUserReadsWrites

4

2 回答 2

1

不,您不能将 BSON 文档读取器/写入器重用为 JSON 读取/写入。但是,您可以重用 JSON 读/写作为 BSON 文档读取器/写入器。您想使用 aJSONCollection从 play-reactive-mongo-plugin 访问数据库,然后将您的 BSON 文档读取器/写入器重写为 JSON 读取/写入。您可以在 play-mongo-knockout 激活器模板中看到执行此操作的示例:

https://github.com/typesafehub/play-mongo-knockout

于 2014-01-01T20:05:28.813 回答
1

如果您仍在寻找更复杂的示例,我将在 3 小时后完成此操作。它是模型自动写入的基本实现,它使用 10 行代码验证 json 请求并存储到集合中:) 您不需要在控制器中重复插入

https://github.com/MilosMosovsky/play-reactivemongo-models

于 2015-06-25T23:10:28.573 回答