I am using play2-reactivemongo
version 0.11.11 and reactivemongo-play-json
. I have the following class:
case class Player(
id: Option[String],
profiles: List[Profile],
teams: List[Team],
created: Option[DateTime],
updated: Option[DateTime]
) extends Identity
The attribute profiles
is represented as an array which contains elements of Profile
documents (embedded). In contrast, the attribute teams
represents an array of _id
values. However, when working with instances of Player
I want to handle a List
of Team
instances and not _id
values. As a consequence, I think I need my own BSONReader
and BSONWriter
for this.
My code looks as follows:
implicit val PlayerBSONReader = new BSONDocumentReader[Player] {
def read(doc: BSONDocument): Player =
Player(
doc.getAs[BSONObjectID]("_id") map {
_.stringify
},
// attributes 'profiles', 'teams' missing
doc.getAs[BSONDateTime]("created").map(dt => new DateTime(dt.value)),
doc.getAs[BSONDateTime]("updated").map(dt => new DateTime(dt.value))
)
}
implicit val PlayerBSONWriter = new BSONDocumentWriter[Player] {
def write(player: Player): BSONDocument =
BSONDocument(
"_id" -> player.id.map(BSONObjectID(_)),
// attributes 'profiles', 'teams' missing
"created" -> player.created.map(date => BSONDateTime(date.getMillis)),
"updated" -> BSONDateTime(DateTime.now.getMillis)
)
}
How can I set the attributes profiles
and teams
? Querying the database in a model is a bad practice, isn't it? But how can I set the instances when only having the _id
values?