mongodb / bson-rust

Encoding and decoding support for BSON in Rust
MIT License
400 stars 132 forks source link

Serialization issue with Uuid #466

Closed AzHicham closed 5 months ago

AzHicham commented 6 months ago

Versions/Environment

  1. What version of Rust are you using? 1.77.0
  2. What operating system are you using? Ubuntu 23.04
  3. What versions of the driver and its dependencies are you using? (Run cargo pkgid mongodb & cargo pkgid bson) registry+https://github.com/rust-lang/crates.io-index#mongodb@2.8.2 registry+https://github.com/rust-lang/crates.io-index#bson@2.9.0
  4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version()) db version v7.0.7
  5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)? standalone

Describe the bug

I have a simple collection of this struct Analysis { _id: Uuid, value: f32 } I insert analysis in my collection with this: let res = collection.insert_one(&Analysis { _id: Uuid::new_v4(), value: 0_f32 }, None).await?; dbg!(res)

Then I try to find this analysis in my collection this way:

let filter = doc! {"_id": { "$eq": id } }; // id is a Uuid
let res = collection.find_one(filter, None).await?;

But without success...

I find out that the serialization involved during inserting will insert uuids as Binary::subtype::Generic but the serialization involved during the find will use Binary::subtype::Uuid

Making my find always return None ....

To reproduce:

let options = SerializerOptions::builder().human_readable(false).build();
dbg!(bson::to_bson_with_options(&Uuid::new_v4(), options));

Output:

[src/database/mongodb/analysis.rs:44:9] &filter = Document({
    "_id": Document({
        "$eq": Binary {
            subtype: Generic,
            bytes: [
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                1,
            ],
        },
    }),
})
abr-egn commented 6 months ago

Hi!

Given that you're constructing your UUID with new_v4, I'm guessing that you're using the uuid crate directly. Unfortunately, the Serialize implementation for uuid::Uuid doesn't produce valid BSON UUIDs, for that you'll need to use bson::Uuid.

github-actions[bot] commented 6 months ago

There has not been any recent activity on this ticket, so we are marking it as stale. If we do not hear anything further from you, this issue will be automatically closed in one week.

github-actions[bot] commented 5 months ago

There has not been any recent activity on this ticket, so we are closing it. Thanks for reaching out and please feel free to file a new issue if you have further questions.