Datetime fields in structs are being serialized to String
s instead of ISODate
s when using the Rust Mongo driver prototype. How do I get the fields to be saved as ISODate
?
use chrono::{DateTime, Utc};
use mongodb::oid::ObjectId;
use mongodb::{
coll::Collection, db::Database, db::ThreadedDatabase, error::Error, Client, ThreadedClient,
};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Person {
pub _id: ObjectId,
pub date: DateTime<Utc>,
}
fn main() {
let client = Client.with_uri("mongodb://localhost:27017").unwrap();
let p = Person {
_id: ObjectId::new().unwrap(),
date: Utc::now(),
};
let document = mongodb::to_bson(p).unwrap().as_document();
if document.is_some() {
client
.db("my_db")
.collection("mycollection")
.insert_one(document, None)
.unwrap();
}
}
On querying the DB, the record contains a date string (in ISO format); I expected it to be an ISODate
.
You can choose deserialization as ISO string with serde_helpers.
https://docs.rs/bson/1.2.2/bson/serde_helpers/index.html
use mongodb::bson::DateTime;
use mongodb::bson::serde_helpers::bson_datetime_as_iso_string;
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Person {
pub _id: ObjectId,
#[serde(with = "bson_datetime_as_iso_string")]
date: DateTime,
}
With mongodb and bson crates in version 2.0.0-beta.1
In Cargo.toml, add the feature chrono-0_4:
bson = { version = "2.0.0-beta.1", features = ["chrono-0_4"] }
Then annotate your field with
use chrono::{DateTime, Utc};
#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
date: DateTime<Utc>,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With