MongoDb: How let mongodb inserts the _id field?

Hi,

I use mongodb in my project. I have a structure that I want to add in a collection :

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DenSettings{
    #[serde(rename = "_id")]  // Use MongoDB's special primary key field name when serializing
    pub id: String,
    pub property: String,
} 

I don't want to generate the ID myself, but I want to let mongodb add it. Of course, my struct can't exist without a field id so I put "" by default. So when I serialize it as a document to insert it, mongo consider my document with an id and set it to "". Of course, if I remove the id field from my struct, mongo will add it, but when I will read the database, I will not get the ID and I want it.

Is there a way to do that ? What I did for now is to create the ObjectId myself, but not sure it is the way to do.
bson::oid::ObjectId::new().unwrap().to_string()

Thanks

Have a look at the User struct definition in the Getting Started section of the wither ORM built on top of the Rust MongoDB driver. It might be the approach you’ll need to take.

https://github.com/thedodd/wither

1 Like