mongodb / bson-rust

Encoding and decoding support for BSON in Rust
MIT License
405 stars 134 forks source link

How to deserialize ISO formatted json into Bson::DateTime #472

Closed Bryson14 closed 7 months ago

Bryson14 commented 8 months ago

Versions/Environment

  1. What version of Rust are you using?
  2. What operating system are you using?
  3. What versions of the driver and its dependencies are you using? (Run cargo pkgid mongodb & cargo pkgid bson)
  4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version())
  5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)?

Describe the bug

A clear and concise description of what the bug is.

The Code I'm using to test this looks like this:

    #[test]
    fn test_bson_datetime_parsing() {
        let dt = bson::DateTime::now();
        let s = dt.to_string();
        let iso = dt.try_to_rfc3339_string().unwrap();
        let doc = doc!{ "time": dt };
        let json = json!({"time": dt});
        println!("df: {dt}, s: {s}, iso: {iso}, doc: {doc}, json: {json}");
        let iso_string = "2024-04-05T19:24:00.408Z";
        let json_str = format!(
            r#"{{
                "time": {{"$date" : {{"$numberLong":"{}"}} }}, "id": "{}"
            }}"#,
            "1674504029491", "390f5f21-631a-463d-88a5-ebc29ca8a6e3"
        );
        let parsed: BsonTester = serde_json::from_str(&json_str).unwrap();
        println!("{}", parsed.time.unwrap().try_to_rfc3339_string().unwrap())
    }

But the main issue is that I want the user to be able to see a json object like:

{
    "time": "2024-04-05T19:24:00.408Z"
}

And this could then be deserialized with serde_json automatically with a struct like this:

#[derive(Deserialize, Serialize, Debug)]
    struct BsonTester {
        time: Option<bson::DateTime>,
        id: Option<bson::Uuid>
    }

That way the client doesn have to deal with this mess of $date { $numberLong } when sending data to or from the web server

abr-egn commented 7 months ago

I think the bson_datetime_as_rfc3339_string helper will do exactly what you're looking for here 🙂