我有一个case类,它由两个嵌入的文档组成,其中一个是列表。我在检索列表中的项目时遇到一些问题。
请参阅下面的代码:
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]
,这对我来说没有任何意义。
您正在执行以下操作:
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)
}