-->

如何使用ReactiveMongo与枚举?(How to use ReactiveMongo wit

2019-10-23 19:20发布

我对游戏框架和ReactiveMongo工作。 我试图写一个读者和我的课叫做平台作家。 我想用我的斯卡拉枚举创建的类型,但我不知道该读/写器语法应该如何界定。 有人可以帮我找出正确的语法?

import reactivemongo.bson._

sealed trait PlatformType { def name: String }
case object PROPER extends PlatformType { val name = "PROPER" }
case object TRANSACT extends PlatformType { val name = "TRANSACT" }
case object UPPER extends PlatformType { val name = "UPPPER" }


case class Platforms(
  id: Option[BSONObjectID],
  Platform: PlatformType,
  Active: Boolean,
  SystemIds:List[String],
  creationDate: Option[DateTime],
  updateDate: Option[DateTime])

object Platforms {

 implicit object PlatformsBSONReader extends BSONDocumentReader[Platforms] {
   def read(doc: BSONDocument): Platforms =
     Platforms(
       doc.getAs[BSONObjectID]("_id"), 
       doc.getAs[PlatformType]("Platform").get, 
       doc.getAs[Boolean]("Active").get,
       doc.getAs[List[String]]("SystemIds").get, 
       doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)),
       doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value)))
 }  

 implicit object PlatformsBSONWriter extends BSONDocumentWriter[Platforms] {
    def write(platforms: Platforms): BSONDocument =
      BSONDocument(
        "_id" -> platforms.id.getOrElse(BSONObjectID.generate),
        "Platform" -> platforms.Platform,
        "Active" -> platforms.Active,
        "SystemIds" -> platforms.SystemIds,
        "creationDate" -> platforms.creationDate.map(date => BSONDateTime(date.getMillis)),
        "updateDate" -> platforms.updateDate.map(date => BSONDateTime(date.getMillis)))
  } 
}

Answer 1:

对于PlatformType

implicit object PTW extends BSONWriter[PlatformType, BSONString] {
  def write(t: PlatformType): BSONString = BSONString(n.type)
}
implicit object PTR extends BSONReader[BSONValue, PlatformType] {
  def read(bson: BSONValue): PlatformType = bson match {
    case BSONString("PROPER") => PROPER
    // ...
  }
}

有一个在线文档有关BSON读者和作家ReactiveMongo。



文章来源: How to use ReactiveMongo with an enum?