0

我有Play 2.3應用程序與反應性mongo插件。 我有基本文檔:在玩!應用程序基礎文檔字段不會持久化到mongo db(反應性mongo插件)

trait TemporalDocument { 
    val created: Option[DateTime] = Some(new DateTime()) 
    val updated: Option[DateTime] = Some(new DateTime()) 
} 

和具體文件之一:

case class User(name: String) extends TemporalDocument 

object User{ 
    implicit val userFormat = Json.format[User] 
} 

所以,當我堅持它蒙戈DB使用反應蒙戈插件僅僅名堅持着,創建/更新的字段是不是。

我的庫看起來像是:

trait MongoDocumentRepository[T <: TemporalDocument] extends ContextHolder { 

    private val db = ReactiveMongoPlugin.db 

    def insert(document: T)(implicit writer: Writes[T]): Future[String] = { 
    collection.insert(document).map { 
     lastError => lastError.toString 
    } recover { 
     case e: Exception => sys.error(e.getMessage) 
    } 
    } 

    private def collection: JSONCollection = db.collection[JSONCollection](collectionName) 

    implicit object BSONDateTimeHandler extends BSONHandler[BSONDateTime, DateTime] { 
    def read(time: BSONDateTime) = new DateTime(time.value) 

    def write(jdtime: DateTime) = BSONDateTime(jdtime.getMillis) 
    } 
} 

問題是,我將有很多的文件從基本的文檔擴展,我不想初始化這些日期,可能有一些其他領域的每一次。是否有可能做這樣的事情?

回答

2

首先,我們可以減半問題的表面積; Reactive Mongo和/或Play Reactive Mongo插件在這裏並不相關,它是Play's JSON macros,它們負責構建適當的JSON結構(在這種情況下)。

如果我成立了一個TemporalDocumentUser在你的代碼,然後寫出來:

val user = User("timmy") 

println(Json.toJson(user)) 

我得到:

{"name":"timmy"} 

我還沒有研究,但我懷疑這是因爲createdupdated字段未出現在User案例類別的「字段列表」中。

如果我返工你的代碼有點像這樣:

trait TemporalDocument { 
    val created: Option[DateTime] 
    val updated: Option[DateTime] 
} 

case class User(
       name: String, 
       val created: Option[DateTime] = Some(new DateTime()), 
       val updated: Option[DateTime] = Some(new DateTime())) 
       extends TemporalDocument 

然後在相同的測試代碼從播放JSON所需的行爲:

{"name":"timmy","created":1410930805042,"updated":1410930805071} 
+0

你甚至不需要'VAL在'User'構造函數中,因爲case類的構造函數參數默認是public'val's – yahor 2016-06-08 01:36:02