1

我正在用 reactivemongo 做测试

在我的控制器中,我有这个:

package controllers

import models._
import models.JsonFormats._
import play.modules.reactivemongo.MongoController
import scala.concurrent.Future
import reactivemongo.api.Cursor
import org.slf4j.{LoggerFactory, Logger}
import javax.inject.Singleton
import play.api.mvc._
import reactivemongo.api.collections.default.BSONCollection
import reactivemongo.bson._


@Singleton
class Users extends Controller with MongoController {


  private final val logger: Logger = LoggerFactory.getLogger(classOf[Users])

  val collection = db[BSONCollection]("users")

  // list all articles and sort them
  def list = Action.async { implicit request =>


  // get a sort document (see getSort method for more information)
    val sort = getSort(request)
    // build a selection document with an empty query and a sort subdocument ('$orderby')
    val query = BSONDocument(
      "$orderby" -> sort,
      "$query" -> BSONDocument())
    val activeSort = request.queryString.get("sort").flatMap(_.headOption).getOrElse("none")
    // the cursor of documents
    val found = collection.find(query).cursor[User]
    // build (asynchronously) a list containing all the articles
    found.collect[List]().map { users =>
      Ok(views.html.admin.list(users, activeSort))
    }.recover {
      case e =>
        e.printStackTrace()
        BadRequest(e.getMessage())
    }
  }

  ...........

}

在我的模型中,我有这个:

封装模型

import reactivemongo.bson._


case class User(
  nickName: String,
  email:    String,
  password: String,
  active: Boolean
)

object JsonFormats {

  import play.api.libs.json.Json
  // Generates Writes and Reads for Feed and User thanks to Json Macros
  implicit val userFormat = Json.format[User]

}

当我编译项目时返回以下错误:

找不到参数读取器的隐式值:reactivemongo.bson.BSONDocumentReader[models.User]

在这一行是问题:

val found = collection.find(query).cursor[User]

谁能告诉我我错在哪里或我错过了什么?

4

2 回答 2

7

您没有定义隐式处理程序来将您的模型类映射到BSONDocument. 你可以自己实现它,或者,就像你为 做的那样JsonFormats,你可以使用ReactiveMongo 提供的宏

object BsonFormats {
  import reactivemongo.bson.Macros

  implicit val userFormat = Macros.handler[User]

}

BSONCollection或者,您可以使用Play-ReactiveMongoJSONCollection提供的代替 ,使用您已经定义的 JSON 格式执行映射。

于 2014-06-06T02:45:04.373 回答
0

对我来说,即使我已经声明了bsonjson格式的隐式,我仍然会收到错误消息。我需要做的就是导入这个:

import reactivemongo.api.commands.bson.BSONCountCommandImplicits._

于 2017-10-16T10:57:00.393 回答