我最近在scala case类中添加了一个新字段,因为我想开始在MongoDB中跟踪该字段。
假设case类是这样的:
case class MyItem (
var existingField: String,
var newlyAddedField: String
) {
}我使用它来序列化/反序列化json和bson到我的对象:
object MyItem {
import play.api.libs.json.Json
// generate reader and writer:
implicit var jsonFormats = Json.format[MyItem]
implicit var bsonFormats = Macros.handler[MyItem]
}因为我的数据库中的所有现有数据都没有newlyAddedField,所以我得到了运行时异常
reactivemongo.bson.exceptions.DocumentKeyNotFound: The key 'newlyAddedField' could not be found in this document or array有人能帮上忙吗?我读过关于编写我自己的序列化/反序列化的文章,但我不确定如何做,因为我使用的是Play Framework,它的语法和方法在不同的版本中都是不同的。我希望有一种更简单的方法,因为在NoSQL db中添加字段应该是很常见的。顺便说一句,我使用的是play framework 2.5
提前感谢!
发布于 2017-12-17 13:45:35
AFAIU it Macros.handler is null-safe,也就是说,如果没有字段,它不会将值设置为null。我认为在Scala中最简单、最干净的修复方法就是将你的新字段声明为Option[String],这样每个人(包括宏代码生成器)都会看到这个字段可能不存在。这似乎也是the doc suggests所说的
https://stackoverflow.com/questions/47852362
复制相似问题