bson-rust
bson-rust copied to clipboard
RUST-1110 bson::to_vec fail to serialize any `Serialize`
When trying to serialize Serialize object using bson::to_vec it gets to update_element_type which returns an error if the top level object is not ElementType::EmbeddedDocument
if matches!(t, ElementType::EmbeddedDocument) {
Is there a reason for this limitation? I tested the code without this check and it works.
I think I found the issue the problem is that I'm trying to serialize a Vec<Value> which gets me to this piece of code:
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
self.update_element_type(ElementType::Array)?;
DocumentSerializer::start(&mut *self)
}
Which just can't work.... Since ElementType::Array doesn't match ElementType::EmbeddedDocument
In BSON, the only supported top-level type is a document, unlike JSON (for example) which supports any of its types at the top level (see https://bsonspec.org/spec.html and https://www.json.org/json-en.html). For this reason, bson::to_vec raises an error if the value produced is not a document, since it wouldn't be valid BSON.
We do plan to eventually introduce a bson::to_raw_bson method, which would output a RawBson value and could successfully serialize values that don't serialize to documents at the top level. You can follow RUST-1110 to track progress on that. We currently haven't prioritized that work though, since it would require a decent amount of refactoring in the serializer and represents a somewhat niche use case. If you don't mind me asking, what is your use case for serializing the Vec<Value> at the top level?