0

我正在使用play2-reactivemongo版本0.11.11和reactivemongo-play-json。我有以下類:如何爲嵌套和引用文檔創建自定義BSON讀寫器?

case class Player(
       id: Option[String], 
       profiles: List[Profile], 
       teams: List[Team], 
       created: Option[DateTime], 
       updated: Option[DateTime] 
       ) extends Identity 

屬性profiles被表示爲其中包含的Profile文檔(嵌入的)元件的陣列。相反,屬性teams表示值爲_id的數組。但是,在處理Player實例時,我想要處理ListTeam實例,而不是_id值。因此,我認爲我需要我自己的BSONReaderBSONWriter

我的代碼如下:

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

我怎樣才能設置屬性profilesteams?在模型中查詢數據庫是一種不好的做法,不是嗎?但是,如何在只有_id值時設置實例?

回答

0

在那裏您需要確保BSONReader實例可用於任何嵌套類型(例如Profile)。

相同的要求是遞歸的(例如,如果Profile本身具有自定義類型作爲屬性)。

我認爲你需要閱讀更多關於類型類原則,瞭解它如何遞歸地工作,至於Play JSON Reads | Writes,或者BSON類型類。

+0

好的,謝謝,但這隻回答了我的問題的一部分。我如何設置類Team'的實例列表,但只在相應的'User'文件中將它們的'_id'值存儲爲一個數組? –