-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Minor - P4
-
Affects Version/s: None
-
Component/s: BSON
Right now, users can leverage the bson::DateTime type to ensure their datetimes get serialized as datetime's in the database. This type produces extended-JSON formatted output when serialized to other formats though, which is usually not the most ergonomic. We should introduce some logic into the serializer using special newtype names to serialize datetimes correctly in BSON but will allow them to be serialized as strings otherwise, similar to what we did for UUID.
Note that this can't be added by the default bson::DateTime struct, as that would be a breaking change. We could possibly enable this via feature flag, by adding a new serde helper, or introducing a new type.
Here's an example of the desired output:
#[derive(Serialize)] struct MyData { dt: bson::DateTime } let d = MyData { dt: bson::DateTime::now() }; let bson = bson::to_document(&d)?; // { "dt": DateTime(...) } let json = serde_json::to_string(&d)?; // { "dt": "2022-MM-DD-..." }
Originally reported on GitHub at https://github.com/mongodb/bson-rust/issues/191
We should also consider doing this for ObjectId.