Json ReactiveMongo:如何使用投影

Json ReactiveMongo:如何使用投影,json,mongodb,scala,reactivemongo,Json,Mongodb,Scala,Reactivemongo,在使用ReactiveMongo从MongoDB查询文档时,我试图过滤掉密码字段: val projection = Json.obj("password" -> 0) def find(selector: JsValue, projection: Option[JsValue]) = { val query = collection.genericQueryBuilder.query(selector) projection.map(query.projection(_))

在使用ReactiveMongo从MongoDB查询文档时,我试图过滤掉
密码
字段:

val projection = Json.obj("password" -> 0)

def find(selector: JsValue, projection: Option[JsValue]) = {
  val query = collection.genericQueryBuilder.query(selector)
  projection.map(query.projection(_))
  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}
上面的代码无效。。。我还得到了
密码
字段。如果我尝试从mongo客户端执行以下操作,那么它会工作,并且不会返回
password

db.users.find( { username: 'j3d' }, { password:0} )
我遗漏了什么吗?

以下是解决方案:

def find(selector: JsValue, projection: Option[JsValue]) = {
  var query = collection.genericQueryBuilder.query(selector)
  projection.map(query = query.projection(_))

  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}
或者:

def find(selector: JsValue, projection: Option[JsValue]) = {
  val query = collection.genericQueryBuilder
    .query(selector)
    .projection(projection.getOrElse(Json.obj())

  query.cursor[JsValue].collect[Vector](perPage).transform(
    success => success,
    failure => failure match {
      case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
    }
  )
}
我希望这有帮助