Join GitHub today
Fix problems deserializing Bson long into int #913
Adds the ability to deserialize a Bson long into a native int. This could be problematic for numbers outside the range of int but it should probably be checked by the developer if they are taking Bson input. This caused quite a headache when we have data coming from a Json api and wanted to merge with the Bson from MongoDB before deserializing.
This code previously did not work:
int dest; auto jsonSource = Json(2048); // Imagine this came from a web request assert(jsonSource.type == Json.Type.int_); // The Json type is int auto source = Bson.fromJson(jsonSource); // We could do this so we can merge with a Bson object loaded from the database assert(source.type == Bson.Type.long_); // The Bson object now has a long dest.deserializeBson(source); // This caused an error as it was conversion from long to int
@Geod24 I've updated the code to add an assertion for that situation. Frankly I'm torn as to whether the serializer should be checking this. You mention returning an invalid value to the user, but realistically a developer should be using long if there is any chance that the data is going to go outside of int range. We do our range checking in the controllers, well before the point of attempting to coerce it into a native variable.
I've only patched this because it was becoming seriously problematic for us and we are already looking forward with the std_data_json library and figure that the bson library will be replaced in a similar fashion in the near(ish) future.