0

I have went through some of the reactive mongo example and find the conversion of the model and the bson object as below.

  case class Artist(  
  name: String,
  slug: String,
  artistId: Int,
  albums: Vector[Album] = Vector(),
  id: ObjectId = new ObjectId())

object ArtistMap {  
  def toBson(artist: Artist): DBObject = {
    MongoDBObject(
      "name"     -> artist.name,
      "slug"     -> artist.slug,
      "artistId" -> artist.artistId,
      "albums"   -> artist.albums.map(AlbumMap.toBson),
      "_id"      -> artist.id
    )
  }

  def fromBson(o: DBObject): Artist = {
    Artist(
      name = o.as[String]("name"),
      slug = o.as[String]("slug"),
      artistId = o.as[Int]("artistId"),
      albums = o.as[MongoDBList]("albums").toVector
        .map(doc => AlbumMap.fromBson(doc.asInstanceOf[DBObject])),
      id = o.as[ObjectId]("_id")
    )
  }
}

Is there any other way to get rid of this overhead of mapping each field of the case classes, maybe some framework over reactivemongo or any utility for this?

Pranjut
  • 1,747
  • 5
  • 18
  • 31
  • ReactiveMongo offers Macros which create this boilerplate for you. http://reactivemongo.org/releases/0.9/api/index.html#reactivemongo.bson.Macros$ – Otto Dec 23 '14 at 22:59
  • But Macros is not useful when nested object references lies. Macros only does half part. – Pranjut Dec 24 '14 at 02:38
  • What exactly do you mean? Macros can cope with nested classes?! – Otto Dec 25 '14 at 21:33

1 Answers1

0

I don't understand your comment too, but my assumption you want functionality like that. (I haven't written on scala for a few month, so sorry for any stupid mistake.)

case class Album(name: String, year: Int)
/*
then you may implement serialization interface(trait) or use macros
*/
implicit val albumHandler = Macros.handler[Album]
/*
I'm not sure is there build in implementation for the Vector[].
*/
object VectorHandler[T](implicit handler: BSONHandler[BSONValue, T]) extends BSONHandler[BSONArray, Vector[T]]{

 def  read(bson: BSONArray): Vector[T]{
 /* 
iterate over array and serialize it in a Vector with a help of the handler,
or just persist Vector[] as List[] 
*/
 }
def write(t: Vector[T]): BSONArray {

 } 
}

implicit val albumVectorHandler = VectorHandler[Album]()
implicit val artistHandler = Macros.handler[Atrist]
sh1ng
  • 2,808
  • 4
  • 24
  • 38