Question

I'm trying to filter out the password field when querying a document from MongoDB with ReactiveMongo:

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

The code above has no effect... I also get the password field. If I try the following from the mongo client, then it works and password is not returned:

db.users.find( { username: 'j3d' }, { password:0} )

Am I missing something?

Was it helpful?

Solution

Here is the solution:

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

or alternatively:

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

I hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top