使用ReactiveMongo库表示要存储在mongo中的产品



我正在尝试为我的mongodb集合"products"建模一个产品。

看起来是这样的:

{
"_id": "abc123",  
"sku": "sku123",
"name": "some product name",
"description": "this is a description",
"specifications": {
"name" : "name1",
"metadata": [
{"name1": "value1"},
{"name2": "value2"},      
]
}
}

所以我的案例类看起来像:

case class Product(
id: String,
sku: String,
name: String,
description: String,
specifications: Specification
)
case class Specification(
name: String,
metadata: Metadata
)
case class Metadata( 
kvp: Map[String, String]
)

所以现在我必须为每种类型的Product、Specification和Metadata创建处理程序,这样当数据读/写到mongo时,它将执行正确的数据映射?

我将如何映射元数据案例类,有点困惑?

如文档中所示,Reader/Writer在大多数情况下都可以简单地生成。

import reactivemongo.api.bson._
// Add in Metadata companion object to be in default implicit scope
implicit val metadataHandler: BSONDocumentHandler[Metadata] = Macros.handler
// Add in Specification companion object to be in default implicit scope
implicit val specHandler: BSONDocumentHandler[Specification] = Macros.handler
// Add in Product companion object to be in default implicit scope
implicit val productHandler: BSONDocumentHandler[Product] = Macros.handler

然后,任何使用BSONReader/Writer类型类的函数都将接受Product/Specification/Metadata:

BSON.writeDocument(Product(
id = "X",
sku = "Y",
name = "Z",
description = "...",
specifications = Specification(
name = "Lorem",
metadata = Metadata(Map("foo" -> "bar"))))).foreach { doc: BSONDocument =>
println(BSONDocument pretty doc)
}
/* {
'id': 'X',
'sku': 'Y',
'name': 'Z',
'description': '...',
'specifications': {
'name': 'Lorem',
'metadata': {
'kvp': {
'foo': 'bar'
}
}
}
} */

最新更新