在Lift中,无法获取MongoCaseClassListField来存储和恢复类型提示

时间:2014-03-18 05:46:02

标签: mongodb scala serialization lift case-class

在试图让MongoCaseClassListField工作了几个小时后,我想我已经非常接近了。我甚至在REPL的输出JSON中得到了一个类型提示。但是当我需要时,我似乎无法让我的Record类看到格式定义。

scala> import bootstrap.liftweb._
scala> import com.mypackage.model._
scala> import net.liftweb.json._
scala> import net.liftweb.json.JsonDSL._
scala> import net.liftweb.json.JsonAST
scala> new Boot().boot

scala> val jobject1 = ("vid" -> "aaa") ~ ("title" -> "bbb") ~ ("description" -> "ccc") ~ ("time" -> 1234)
rv1: net.liftweb.json.JsonAST.JObject = JObject(List(JField(vid,JString(aaa)), JField(title,JString(bbb)), JField(description,JString(ccc)), JField(time,JInt(1234))))

scala> val videoitem1 = VideoItem.create(jobject1)(MediaLibrary.formats)
vi1: com.mypackage.model.VideoItem = VideoItem(aaa,bbb,ccc,1234.0,List())

scala> val ml = MediaLibrary.createRecord.libraryName("Test3").libraryItems(videoitem1 :: Nil) # NOTE: No JsonClass field !!!
mi1: com.mypackage.model.MediaLibrary = class com.mypackage.model.MediaLibrary={libraryItems=List(VideoItem(aaa,bbb,ccc,1234.0,List())), _id=53278cb7ccf2ebe412398548, libraryName=Test3}

scala> ml.save
res1: com.mypackage.model.MediaLibrary = class com.mypackage.model.MediaLibrary={libraryItems=List(VideoItem(aaa,bbb,ccc,1234.0,List())), _id=53278cb7ccf2ebe412398548, libraryName=Test3}

这是指以下代码:

trait LibraryItem


case class VideoItem (
  vid: String,
  title: String,
  description: String,
  time: Double,
  tags: Seq[String]) extends LibraryItem with JsonObject[VideoItem] {
  def meta = VideoItem
}

object VideoItem extends JsonObjectMeta[VideoItem]

case class LinkItem (
  url: String,
  title: String,
  tags: Seq[String]) extends LibraryItem with JsonObject[LinkItem]   {
  def meta = LinkItem
}

object LinkItem extends JsonObjectMeta[LinkItem]

class MediaLibrary extends MongoRecord[MediaLibrary] with ObjectIdPk[MediaLibrary] {
  def meta = MediaLibrary

  object libraryName extends StringField(this, 256)
  object libraryItems extends MongoCaseClassListField[MediaLibrary, LibraryItem](this)
}

object MediaLibrary extends MediaLibrary with MongoMetaRecord[MediaLibrary] {
  override def formats = Serialization.formats(ShortTypeHints(List(classOf[VideoItem], classOf[LinkItem])))
}

我可以给Mongo写一条记录,但是从来没有类型提示。我可以返回一个记录,但它总是返回一个库列表的空列表。

白天,这段代码有很多种变化。但我不知道要去哪个方向。

理想情况下,当然,我想要的是创建MediaLibrary,其项目为VideoItemLinkItem。在查询数据库时,我想要一个LibraryItem的列表,我可以将它与两个案例类进行模式匹配,或者甚至是两个案例类的实例列表。我一定错过了什么,但是什么?

1 个答案:

答案 0 :(得分:0)

formats被定义在错误的地方!

这有效:

class MediaLibrary extends MongoRecord[MediaLibrary] with ObjectIdPk[MediaLibrary] {
  def meta = MediaLibrary

  object libraryName extends StringField(this, 256)
  object libraryItems extends MongoCaseClassListField[MediaLibrary, LibraryItem](this){
    override def formats = Serialization.formats(ShortTypeHints(List(classOf[VideoItem], classOf[LinkItem])))
  }
}

object MediaLibrary extends MediaLibrary with MongoMetaRecord[MediaLibrary]