I'm trying to return a json with a datetime from MongoDB, here is my struct
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Management {
// .. other properties
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
pub created_at: DateTime<Utc>,
}
the problem is that what I'm getting is:
{
"createdAt": {
"$date": {
"$numberLong": "1634685582291"
}
}
}
instead of
{createdAt: 2021-06-24T04:00:00Z}
I tried to create my own serialization method but then it was saving strings in the database instead of dates.
Can someone give me hand?
CodePudding user response:
The problem is that you are using Serde's with
, which is used for both serialization and deserialization. From the [documentation][1]:
#[serde(with = "module")]
Combination of serialize_with and deserialize_with. Serde will use $module::serialize as the serialize_with function and $module::deserialize as the deserialize_with function.
Edit:
The solution would be to create another structure for the representation of the "outgoing management", where you serialize the date as an ISO string as you want:
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ManagementOutgoing {
// .. other properties
#[serde(with = "your-serializer")]
pub created_at: DateTime<Utc>,
}
And you can implement the From
trait for it so that you can easily convert a Management
instance into a ManagementOutgoing
.