我在使用ReactiveMongo从MongoDB查询文档时尝试过滤掉password
字段:
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))
}
)
}
上面的代码没有效果......我也得到了password
字段。如果我从mongo客户端尝试以下操作,那么它可以工作,并且不会返回password
:
db.users.find( { username: 'j3d' }, { password:0} )
我错过了什么吗?
答案 0 :(得分:2)
以下是解决方案:
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))
}
)
}
我希望有所帮助。