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?
play.api.libs.json.Json
with BSONObjectId
?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]
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With