Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle MongoDB ObjectIds in Play framework using Reactivemongo?

I have a basic model with a case class

case class Record( id: Option[String], 
                 data: Double,
                 user: String,
                 )

object RecordJsonFormats {
  import play.api.libs.json.Json

  implicit val recordFormat = Json.format[Record]
}

Field user is actually an ObjectId of other module also id is also an ObjectId yet then try to change String type to BSONObjectId macros in play.api.libs.json.Json break... so both user and if saved with object id fields get saved as String not ObjectId.

What is the optimal way to operate with ObjectIds in Play framework?

  • Maybe I should extend play.api.libs.json.Json with BSONObjectId?
  • Maybe there is a way to link models and IDs are tracked automatically without a need to declare them in model?
like image 782
PovilasID Avatar asked Mar 06 '15 19:03

PovilasID


2 Answers

You can override the default type of _id. You just need to specify the type you want in the case class.

import java.util.UUID
import play.api.libs.json._

case class Record (_id: UUID = UUID.randomUUID())

object Record {
  implicit val entityFormat = Json.format[Record]
}
like image 55
Rémi Lavolée Avatar answered Oct 03 '22 22:10

Rémi Lavolée


MongoDB has a default _id field of type ObjectId, which uniquely identifies a document in a given collection. However, this _id typically does not have a semantic meaning in the context of the application domain. Therefore, a good practice is to introduce an additional id field as index of documents. This id can simply a Long number, no more or less.

Then, you can search documents by id easily, and do not care much about ObjectId.

This, https://github.com/luongbalinh/play-mongo/, is a sample project using Play 2.4.x and ReactiveMongo. Hopefully, it helps you.

like image 26
Luong Ba Linh Avatar answered Oct 03 '22 22:10

Luong Ba Linh