ReactiveMongo Macros.handler crashes after new field is added

301 Views Asked by At

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!

1

There are 1 best solutions below

0
On

AFAIU it Macros.handler is null-safe i.e. it doesn't sets value to null if there is no field. I think the simplest and the cleanest fix this in Scala is to declare your new field as Option[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