【问题标题】:How do I serialize chrono::DateTime fields as ISODate when using the Rust Mongo driver prototype?使用 Rust Mongo 驱动程序原型时,如何将 chrono::DateTime 字段序列化为 ISODate?
【发布时间】:2019-04-17 21:06:55
【问题描述】:

当使用Rust Mongo driver prototype 时,结构中的日期时间字段被序列化为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();
    }
}

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

【问题讨论】:

  • 尝试使用UtcDateTime
  • 是的,我知道UtcDatetime 会起作用。然而,就像i32i64String 一样,我不必在我的结构中使用bson::Bson::Stringbson::Bson::I32bson::Bson::I64,序列化程序应该透明地处理转换。在结构字段上添加变体也是一种可接受的解决方案。
  • 那不可能mongodb 不能为Serialize 实现DateTime,他们需要一个包装器,看起来bson 拥有它并分享它。为什么不使用它?
  • 官方驱动也有同样的问题。如果我放置一个序列化的结构,它会写入一个字符串,但是当我使用带有Utc 的 doc 更新它时,它会写入无法反序列化的数据????

标签: mongodb rust bson serde


【解决方案1】:

您可以使用 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,
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多