我对 BSONDocuments 在应用程序中处理可选值的方式有困难。我从 Typesafe 激活器(play/reactivemongo/angular)的“最终”模板开始。我创建了一个表示要进入 Mongo 的对象的案例类,其中一些值是选项:
case class Item(
id: Option[BSONObjectID],
manufacturer: String,
minPrice: Option[Double],
maxPrice: Option[Double])
我遇到的问题是可选值作为数组写入 Mongo。例如,使用“Acme”作为制造商,88 作为 minPrice,None 作为 maxPrice。Mongo 中的 Printjson 显示这看起来像
{
_id = BSONObjectID("...")
manufacturer: "Acme",
maxPrice: [ ],
minPrice: [
88
]
}
从数据库值创建对象时,我无法将 Mongo 中的数组值作为简单的选项值读回。
Item(
....
bsondoc.getAs[Double]("minPrice"),
....
)
尽管 bsondoc.get("minPrice") 确实具有值 Some(BSONDocument()),但 getAs() 语句始终返回 None
我打印了发送到 Mongo 进行更新的数据,果然,创建修饰符语句的代码将可选值作为数组发送,可以是空的,也可以包含一个元素。
val modifier = BSONDocument(
"$set" -> BSONDocument(
"manufacturer" -> manufacturer,
"minPrice" -> minPrice,
"maxPrice" -> maxPrice
))
这个漂亮的打印为
{
$set: {
manufacturer: BSONString(Acme),
maxPrice: [
],
minPrice: [
0: BSONDouble(88.0)
]
}
}
是否有正确的方法来处理这些可选值?
为了增加神秘感,我将相同的修饰符创建代码放在工作表中(在 Eclipse 中),我得到了不同的结果:
{
$set: {
manufacturer = BSONString(Acme),
minPrice = BSONInteger(88)
}
}
可选值没有数组。如果它们没有,它们就不会出现。这对我的应用程序来说可以正常工作,但有些东西正在改变应用程序内可选元素的 BSONDocument 处理。有谁知道为什么?