2015-11-11 51 views
0

我想構建一個將Scala案例類轉換爲Mongo文檔的通用方法。如何將Scala案例類轉換爲mongo文件

一個有前途的Document constructor

fromSeq(ts: Seq[(String, BsonValue)]): Document 

我可以把一個案例類到地圖[字符串 - >任何],但後來我失去了我需要使用隱式轉換爲BsonValues類型的信息。也許類型標籤可以幫助這個?

這是我已經試過:

import org.mongodb.scala.bson.BsonTransformer 
import org.mongodb.scala.bson.collection.immutable.Document 
import org.mongodb.scala.bson.BsonValue 

case class Person(age: Int, name: String) 

//transform scala values into BsonValues 
def transform[T](v: T)(implicit transformer: BsonTransformer[T]): BsonValue = transformer(v) 

// turn any case class into a Map[String, Any] 
def caseClassToMap(cc: Product) = { 
    val values = cc.productIterator 
    cc.getClass.getDeclaredFields.map(_.getName -> values.next).toMap 
} 

// transform a Person into a Document 
def personToDocument(person: Person): Document = { 
    val map = caseClassToMap(person) 

    val bsonValues = map.toSeq.map { case (key, value) => 
    (key, transform(value)) 
    } 

    Document.fromSeq(bsonValues) 
} 

<console>:24: error: No bson implicit transformer found for type Any. Implement or import an implicit BsonTransformer for this type. 
      (key, transform(value)) 

回答

1
def personToDocument(person: Person): Document = { 
    Document("age" -> person.age, "name" -> person.name) 
} 
+1

太差勁了作爲一個實際的解決方案。我可以想象只有當我按小時付款時才能這樣做。 –

-1

可以使用薩拉特https://github.com/salat/salat。一個很好的例子可以在這裏找到 - https://gist.github.com/bhameyie/8276017。這是一段代碼,可以幫助你 -

import salat._ 

val dBObject = grater[Artist].asDBObject(artist) 
artistsCollection.save(dBObject, WriteConcern.Safe) 
+0

歡迎訪問解決方案的鏈接,但請確保您的答案在沒有它的情況下很有用:[添加鏈接的上下文](// meta.stackexchange.com/a/8259),以便您的同行用戶瞭解它是什麼以及爲什麼它在那裏,然後引用您鏈接的頁面中最相關的部分,以防目標頁面不可用。 [僅僅是一個鏈接的答案可能會被刪除。](// stackoverflow.com/help/deleted-answers) – paper1111

相關問題