When inserting a document, the Rust driver returns the inserted _id as an Option.
I was wondering why that is and if it is safe to unwrap. Below is a small example of what I mean.
let id = match mongo_client.database("database").collection("collection")
.insert_one(a_document, None).await {
Ok(insert_one_result) => insert_one_result.inserted_id.as_object_id().unwrap(),
Err(e) => return Err(e)
};
Is it possible, on a successful insert, that the Option is ever None and the code above panics?
_id is the only field that must be present in a document and it must be unique.
The official drivers will automatically create an _id field if one is not present when inserting a document. This is usually a generated ObjectId.
Not for your code(assuming no _id: None in the document). However it is possible to explicitly insert a None/null in to the _id field and thus get a None/null back for the inserted_id.
Hi, I’m one of the maintainers of the Rust driver. Bson::as_object_id returns None if the value you call it on is not an ObjectId: Bson in bson - Rust
so if you are using non-ObjectId values for the _id field you could experience a panic here.