MongoDB _id map using Play-Reactivemongo plugin?

I am trying to use the Play-ReactiveMongo plugin to read / write simple records in MongoDB using Play and Angular. The plugin looks like a good option because it allows you to use simple case classes and regular JSON instead of explicitly converting between BSON and JSON. But a few examples of using the plugin do not seem to cover how to map the identifier of a MongoDB object to / from JSON within the same structure. All this seems to work with an implicit load (= magic for me). Reads / writes in the background, but they do not seem to process the object identifier.

My code is based on Alex Lashford. Modern web template and very similar to

+6
source share
2 answers

I solved this problem by creating another case class:

 case class Id($oid: String) 

then use it as follows:

 case class User(_id: Id, ...) 

You must have imported Json converters

 implicit val idFormat = Json.format[Id] implicit val userFormat = Json.format[User] 
+1
source

I do not know why the reactivemongo team decided to have an ObjectId in BSON, but not in JSON. Anyway, you can build a json representation of the MongoDB ObjectId as follows:

 import play.api.libs.json._ def objectId(id: String) = Json.obj("$oid" -> id) yourCollection.find(Json.obj("_id" -> objectId(id))).cursor()... 
+1
source

Source: https://habr.com/ru/post/977970/


All Articles