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

Nir*_*man 5 mongodb bson rust serde

使用Rust Mongo 驱动程序原型时,结构中的日期时间字段被序列化为Strings 而不是ISODates 。如何获取要另存为的字段?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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

使用版本 2.0.0-beta.1 中的 mongodb 和 bson crate

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

bson = { version = "2.0.0-beta.1", features = ["chrono-0_4"] }
Run Code Online (Sandbox Code Playgroud)

然后用注释你的字段

use chrono::{DateTime, Utc};

#[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
date: DateTime<Utc>,
Run Code Online (Sandbox Code Playgroud)