如何使用ReactiveMongo与枚举? [英] How to use ReactiveMongo with an enum?
本文介绍了如何使用ReactiveMongo与枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Play Framework和ReactiveMongo。我正在为我的班级平台写一个读者和作家。我试图使用我创建为scala枚举的类型,但是我不知道如何定义读/写器语法。有人可以帮我找出正确的语法吗?
I am working with the Play Framework and ReactiveMongo. I am trying to write a reader and a writer for my class called Platforms. I am trying to use a type that I created as scala enum, but I don't know how the reader/writer syntax should be defined. Can someone help me figure out the correct syntax?
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)))
}
}
推荐答案
对于 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的作家。
There is an online documentation about the BSON readers & writers in ReactiveMongo.
这篇关于如何使用ReactiveMongo与枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文