ReactiveMongo: How to convert BSON returned by FindAndModify to JSON

mongodb, reactivemongo, scala

Solution

BSON handlers implicits (suggested in comment) might not work because FindAndModify command has a strict signature to return `Option[BSONDocument]`

FindAndModify extends BSONCommandResultMaker[Option[BSONDocument]]

given the returned result is of `Future[Option[BSONDocument]]` type

you can import the json formats

import play.modules.reactivemongo.json.BSONFormats._

and apply

result.map(docOpt => docOpt.map(d => Json.toJson(d)))

on result, or call the conversion directly

import play.modules.reactivemongo.json.BSONFormats

result.map(docOpt => docOpt.map(d =>
  BSONFormats.BSONDocumentFormat.writes(d).as[JsObject]))

Problem

Here below is the code for updating a document with Mongo's `FindAndModify`: ``` val selector = BSONDocument("id" -> "1234") val modifier = BSONDocument("$set" -> BSONDocument("email" -> "new@domain.com")) ReactiveMongoPlugin.db.command(FindAndModify( collection.name, selector, Update(modifier, false), false, None )).transform( success => success.map { s => // doesn't work... Json.fromJson[Seq[JsValue]](toJson(s)).map(for (item <- _) yield item).get }.getOrElse(List[JsValue]()), failure => failure match { case e: LastError => DaoServiceException(e.message, Some(DATABASE_ERROR)) } ) ``` In the `success` block I'm trying to convert the returned `BSONDocument` collection into a `JsValue` collection... but it doesn't work and the resulting `JsValue` collection is always empty (I've verified the `BSONDocument` collection returned by the command and I confirm it is non-empty). Am I missing something?

Original source