0

我有一个由 2 个嵌入文档组成的案例类,其中一个是列表。我在检索列表中的项目时遇到了一些问题。

请在下面查看我的代码:

package models

import play.api.Play.current
import com.novus.salat._
import com.novus.salat.dao._
import com.mongodb.casbah.Imports._
import se.radley.plugin.salat._
import com.novus.salat.global._

case class Category(
  _id: ObjectId = new ObjectId,
  category: Categories,
  subcategory: List[SubCategories]
)

case class Categories(
  category_id: String,
  category_name: String
  )

case class SubCategories(
  subcategory_id: String,
  subcategory_name: String
)

object Category extends ModelCompanion[Category, ObjectId] {
  val collection = mongoCollection("category")
  val dao = new SalatDAO[Category, ObjectId](collection = collection) {}
  val CategoryDAO = dao

  def options: Seq[(String,String)] = {
    find(MongoDBObject.empty).map(it => (it.category.category_id, it.category.category_name)).toSeq
  }

  def suboptions: Seq[(String,String,String)] = {
    find(MongoDBObject.empty).map(it => (it.category.category_id, it.subcategory.subcategory_id, it.subcategory.subcategory_name)).toSeq
  }
}

我得到错误:value subcategory_id is not a member of List[models.SubCategories]这对我没有任何意义。

4

1 回答 1

1

你正在这样做:

def suboptions: Seq[(String,String,String)] = {
  find(MongoDBObject.empty).map(category => {
    val categories: Categories = category.category
    val categoryId: String = categories.category._id
    val subcategory: List[Subcategory] = category.subcategory
    val subcategoryId: String = subcategory.subcategory_id //here you are trying to 
      //get id from list of subcategories, not one of them
    val subcategoryName: String = subcategory.subcategory_name //same here
    (categoryId, subcategoryId, subcategoryName)).toSeq  
  }
}

顺便提一句。在 Scala 中使用snake_case 非常少见,val/var 名称应该使用 camelCase 格式,请参阅

编辑:您可以通过执行以下操作使其变得简单:

case class Category(
  _id: ObjectId = new ObjectId(), 
  id: String,
  name: String,
  subcategories: List[Subcategory]
)
case class Subcategory(
  id: String,
  name: String
)
//not tested
def suboptions: Seq[(String, String, String)] = {
  val categories = find(MongoDBObject.empty)
  for{
    category <- categories;
    subcategory <- category.subcategories
  } yield (category.id, subcategory.id, subcategory.name)
}
于 2012-09-07T07:47:27.090 回答