是不是有任何其他方法将bson对象转换为case类,反之亦然而不是scala中的隐式转换?

时间:2014-12-23 02:22:19

标签: mongodb scala reactivemongo

我已经浏览了一些反应性mongo示例,并找到了模型和bson对象的转换,如下所示。

  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")
    )
  }
}

有没有其他方法可以摆脱映射案例类的每个字段的开销,也许是针对reactivemongo或任何实用程序的一些框架?

1 个答案:

答案 0 :(得分:0)

我也不理解你的评论,但我认为你需要这样的功能。 (我还没有用scala写几个月,很抱歉任何愚蠢的错误。)

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]