使用Rust Mongo驱动程序原型时,如何将chrono :: DateTime字段序列化为ISODate?

时间:2019-04-17 21:06:56

标签: mongodb rust bson serde

使用Rust Mongo driver prototype时,结构中的

Datetime字段将序列化为String而不是ISODate。如何获取要另存为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();
    }
}

查询数据库时,记录中包含日期字符串(ISO格式);我希望它是ISODate

2 个答案:

答案 0 :(得分:2)

您可以使用 serde_helpers 选择反序列化为 ISO 字符串。

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,
}

答案 1 :(得分:1)

在 2.0.0-beta.1 版本中使用 mongodb 和 bson crates

在 Cargo.toml 中,添加功能 chrono-0_4:

bson = { version = "2.0.0-beta.1", features = ["chrono-0_4"] }

然后用

注释您的字段
use chrono::{DateTime, Utc};

#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
date: DateTime<Utc>,