我有一个案例类,由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]
这对我没有任何意义。
答案 0 :(得分: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中,请参阅this
编辑:你可以通过这样做来简化:
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)
}