Why does collection.find_one({ _id: id }) always return nothing even with correct string id?

Viewed 38

I am working on a MongoDB-based API webserver to learn Rust and I can't figure out why I can't get results:

use mongodb::bson::{doc, oid::ObjectId};
use mongodb::{error::Error, Database};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone)]
struct Job {
    _id: ObjectId,
    user_id: String,
    organisation: String,
    role: String,
}

async fn find_job_by_id(database: &Database, id: String) -> Result<Option<Job>, Error> {
    database
        .collection("jobs")
        .find_one(Some(doc! { "_id": id }), None)
        .await
}

I've tried printing out the id at every step and it always looks correct, but .find_one() always returns Ok(None). Any tips?

1 Answers

Turns out filters for ObjectId fields have to be specifically use ObjectId. You can't apply filters using strings as I was doing over there. This method is what fixed it:

let id = ObjectId::parse_str(id).unwrap();

Looks like the myths were true... rust is pretty harsh with type checking...

Related