0

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?

John Doe
  • 275
  • 3
  • 12

1 Answers1

0

There you need to make sure a BSONReader instance is available for any nested type (such as Profile).

The same requirement is recursive (e.g. if Profile itself has custom types as properties).

I think you need to read more about the typeclass principle, to understand how it can work recursively, as for Play JSON Reads|Writes, or for BSON typeclasses.

cchantep
  • 9,118
  • 3
  • 30
  • 41
  • Okay thanks, but this answers only part of my question. How can I set a list with instances of class `Team`, but only store their `_id` values as an array in the corresponding `User` document? – John Doe May 29 '16 at 20:32