It's my understanding that null is the state of a value, and not the type of an value within the MongoDB ecosystem. That is an element should have a key that maps to a certain type of value, and that it's possible that value is null. But the C++ driver doesn't seem to comply with this.
What is the cleanest way to handle the possibility that an element is null using the bsoncxx library? I would think that all types should be convertible to null, but I cannot figure out if or how that would be the case. This is particularly difficult in converting std::optional types into a comparable BSON type. Below is an example of some code that I would like to work, but I haven't been able to find a reasonable work around.
template<typename T>
static auto ToBsonType(const std::optional<T>& v) {
if (v.has_value()) {
return ToBsonType(v.value());
} else {
return bsoncxx::nullopt;
}
}
My serializer works like this, which works well for all types until I get to these nullable types:
static bsoncxx::document::value ToBsonDocument(Class class) {
auto doc = document{}
<< "_id" << ToBsonType(class.id())
<< "a" << ToBsonType(class.a())
<< "b" << ToBsonType(class.b())
<< finalize;
return doc;
}
Any suggestions, or do I need to rewrite the entire API if nullible types cannot be represented as a single type?