I recently add a new field to my scala case class since I want to start keeping track of that field in my MongoDB.
let's say case class is like this:
case class MyItem (
var existingField: String,
var newlyAddedField: String
) {
}
I use this to serialize/deserialize json and bson to my object:
object MyItem {
import play.api.libs.json.Json
// generate reader and writer:
implicit var jsonFormats = Json.format[MyItem]
implicit var bsonFormats = Macros.handler[MyItem]
}
As all the existing data in my db doesn't have newlyAddedField
, I get runtime exception
reactivemongo.bson.exceptions.DocumentKeyNotFound: The key 'newlyAddedField' could not be found in this document or array
Could anyone help? I've read about writing my own serialization/deserialization but I am not sure how to do that as I am using Play Framework whose syntax and way to do things are all different among its versions. I hope there is a simpler way as adding field should be common in NoSQL db. Btw, I am using play framework 2.5
Thanks in advance!
AFAIU it
Macros.handler
isnull
-safe i.e. it doesn't sets value tonull
if there is no field. I think the simplest and the cleanest fix this in Scala is to declare your new field asOption[String]
so everyone (including the macro code-generator) will see that this field might be absent. And this seems to be what the doc suggests as well