结构中的日期时间字段被序列化为 String
s 而不是 ISODate
s 使用 Rust Mongo driver prototype 时.如何将字段保存为 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
.
最佳答案
您可以使用 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,
}
关于mongodb - 使用 Rust Mongo 驱动程序原型(prototype)时,如何将 chrono::DateTime 字段序列化为 ISODate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55735974/