Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize chrono::DateTime fields as ISODate when using the Rust Mongo driver prototype?

Datetime fields in structs are being serialized to Strings instead of ISODates 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.

like image 398
nngg Avatar asked Apr 17 '19 21:04

nngg


2 Answers

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,
}
like image 193
Marek Barvir Avatar answered Oct 16 '22 05:10

Marek Barvir


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>,
like image 27
Ulysse Goarant Avatar answered Oct 16 '22 05:10

Ulysse Goarant