-
Notifications
You must be signed in to change notification settings - Fork 146
Description
I would like to use the mongodb rust driver for my new rest API project, but I am running into issues with the way how bson types (like ObjectId
or Date
) is (de)serialized by default.
An ObjectId
as an example is serialzied to {$oid: ""}
which is great for use in the DB but not what (I assume) most people would like to use in an HTTP API. Similarly DateTime
is not serialized to a string representation, but into a bson one.
I know about the serde_helpers
module but those function do not solve the issue, namely that if I use serialize_object_id_as_hex_string
on my ObjectId field, it will serialize it to a hex string both for my API response (desired) AND before sending it to the database (not desired). The same applies to DateTime <-> chrono::DateTime as well, dates are stored as strings into the db when using the helper method.
My current solution is to create a wrapper type over ObjectId and implement (De)Serialize for it manually the following way:
impl Serialize for ObjectId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
if serializer.is_human_readable() {
serializer.serialize_str(&self.0.to_hex())
} else {
self.0.serialize(serializer)
}
}
}
This works beautifully and I assume this is what 99% of users would expect as well. My question is if it would be possible that this crate would provide such an implementation by default for its types so that I and assume many others could "just use it".
I imagine this could also be put behind a feature flag.
Thanks!