如何正确映射我的对象以使对象列表在mongo + play2中工作

时间:2013-04-28 10:50:36

标签: mongodb scala playframework playframework-2.1

我在阅读后试图为我的案例类编写读者/作者:

但是我在制作它时遇到了麻烦。

我有一个可以包含多个单词对象的leadCategory。

package models

import org.joda.time.DateTime
import reactivemongo.bson._
import reactivemongo.bson.handlers.{BSONWriter, BSONReader}
import reactivemongo.bson.BSONDateTime
import reactivemongo.bson.BSONString

LeadCategory:

case class LeadCategory(
                         id: Option[BSONObjectID],
                         categoryId: Long,
                         categoryName: String,
                         creationDate: Option[DateTime],
                         updateDate: Option[DateTime],
                         words: List[Word]
                         )

object LeadCategory {

  implicit object LeadCategoryBSONReader extends BSONReader[LeadCategory] {
    def fromBSON(document: BSONDocument): LeadCategory = {
      val doc = document.toTraversable
      LeadCategory(
        doc.getAs[BSONObjectID]("_id"),
        doc.getAs[BSONLong]("caregoryId").get.value,
        doc.getAs[BSONString]("categoryName").get.value,
        doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)),
        doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value)),
        doc.getAs[List[Word]]("words").toList.flatten)
    }
  }

  implicit object LeadCategoryBSONWriter extends BSONWriter[LeadCategory] {
    def toBSON(leadCategory: LeadCategory) = {
      BSONDocument(
        "_id" -> leadCategory.id.getOrElse(BSONObjectID.generate),
        "caregoryId" -> BSONLong(leadCategory.categoryId),
        "categoryName" -> BSONString(leadCategory.categoryName),
        "creationDate" -> leadCategory.creationDate.map(date => BSONDateTime(date.getMillis)),
        "updateDate" -> leadCategory.updateDate.map(date => BSONDateTime(date.getMillis)),
        "words" -> leadCategory.words)
    }
  }

Word:

case class Word(id: Option[BSONObjectID], word: String)

object Word {

  implicit object WordBSONReader extends BSONReader[Word] {
    def fromBSON(document: BSONDocument): Word = {
      val doc = document.toTraversable
      Word(
        doc.getAs[BSONObjectID]("_id"),
        doc.getAs[BSONString]("word").get.value
      )
    }
  }

  implicit object WordBSONWriter extends BSONWriter[Word] {
    def toBSON(word: Word) = {
      BSONDocument(
        "_id" -> word.id.getOrElse(BSONObjectID.generate),
        "word" -> BSONString(word.word)
      )
    }

  }    
}

我收到了编译错误:

"words" -> leadCategory.words)

陈述:

Too many arguments for method apply(ChannelBuffer)
Type mismatch found: (String, List[Words]) required required implicits.Producer[(String, BsonValue)]

我错过了什么?也许我误解了文档......

2 个答案:

答案 0 :(得分:0)

所有类型都应该是BSON类型的衍生物。我想你想使用BSONArray而不是List。

答案 1 :(得分:0)

如果要将所有内容放在同一个文件中,请尝试在“LeadCategory”上面声明“Word”隐式对象。

Scala无法找到List [Word]的隐含对象 - 假设您使用的是ReactiveMongo 0.9。