ReactiveMongo: How to convert BSON returned by FindAndModify to JSON

喜欢而已 提交于 2019-12-09 19:35:03

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/21666105/reactivemongo-how-to-convert-bson-returned-by-findandmodify-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!