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
實例時,我想要處理List
的Team
實例,而不是_id
值。因此,我認爲我需要我自己的BSONReader
和BSONWriter
。
我的代碼如下:
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)
)
}
我怎樣才能設置屬性profiles
和teams
?在模型中查詢數據庫是一種不好的做法,不是嗎?但是,如何在只有_id
值時設置實例?
好的,謝謝,但這隻回答了我的問題的一部分。我如何設置類Team'的實例列表,但只在相應的'User'文件中將它們的'_id'值存儲爲一個數組? –