Map MongoDB _id using Play-Reactivemongo plugin?
Asked Answered
C

2

6

I'm trying to use the Play-ReactiveMongo plugin to read/write simple records in MongoDB with Play and Angular. The plugin seems like a nice option as it allows you to use simple case classes and regular JSON instead of explicitly converting between BSON and JSON. But the few examples of using the plugin don't seem to cover how to map the MongoDB Object ID to/from JSON within the same framework. This all seems to work with a load of implicit (= magic to me) Reads/Writes in the background, but they don't seem to handle the Object ID.

My code is based on Alex Lashford's Modern Web Template, and very similar to Stephan Godbillion's example using JSON Read/Writes, but neither Alex nor Stephan shows anything to do with the MongoDB object ID.

I need some kind of unique ID for my data records, so I can fetch and update them etc, and it makes sense to use the one MongoDB provides, but I can't seem to find a way to use this cleanly within the Play ReactiveMongo plugin.

Does anybody know of an example that shows how to use Play ReactiveMongo plugin with JSON collections and some way to map the Object ID to/from JSON without having to convert all my processing to use BSON?

Cadmus answered 10/11, 2014 at 9:10 Comment(2)
If possible you to used scala salat they had good documentation about mongo and scala and easily integrated with play github.com/leon/play-salatLowis
Thanks, yogesh. Salat might be an option, but that would require me to re-work existing code and implement a load of mapping code anyway. The Play ReactiveMongo plugn seems to give me 90% of what I need already, except for the Object ID. If I need to implement some explicit mapping for the Object ID, that's probably still going to be easier than switching to Casbah/Salat. I just need to find out how to do this.Cadmus
F
1

I've solved this issue by creating another case class:

case class Id($oid: String)

then use it as follows:

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

You have to have Json converters imported

implicit val idFormat = Json.format[Id]
implicit val userFormat = Json.format[User]
Foam answered 30/6, 2015 at 9:17 Comment(0)
F
1

I don't know why the reactivemongo team decided to have an ObjectId in BSON, but not in JSON. Anyway, you can construct the 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()...
Frumenty answered 16/8, 2016 at 7:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.