MongoDB Rust driver returning empty cursor collection

31 Views Asked by At

I am trying out the rust mongodb driver with a mongodb cluster that is hosted on mongo's Atlas. But when I call find, and try to collect the results, it is returning an empty vector, even though I know there is data.

I am using actix-web for setting up a web server. When I set up my app, I make the connection to my DB and cluster:

#[actix_web::main]
async fn main() -> anyhow::Result<()> {
    initialize_tracing(Some("firestations_api_rust=debug"));

    tracing::info!(" Starting API on port: {BIND_PORT}");

    let cluster_uri = "mongodb+srv://myusername:[email protected]/?retryWrites=true&w=majority";
    let client = Client::with_uri_str(cluster_uri).await?;

    // Ping Atlas MongoDB to test connection
    client
        .database("FSCluster")
        .run_command(doc! {"ping": 1}, None)
        .await?;
    tracing::info!(" Successfully connection to MongoDB Atlas Server");

    let database = client.database("FireStarter");
    let collection: Collection<FireStation> = database.collection("FEMA_stations");

    let app_state = web::Data::new(AppState {
        client,
        collection: collection.clone(),
    });

    HttpServer::new(move || {
        let app = App::new()
            .app_data(app_state.clone())
            .app_data(collection.clone())
            .service(station::list);

        return app;
    })
    .bind((BIND_ADDRESS, BIND_PORT))?
    .run()
    .await?;

    Ok(())
}

The ping to the DB is successful. In a GET route, I am just testing out a simple collection.find function using a query that I know should return results:

#[get("/v1/stations")]
pub async fn list(req: HttpRequest, state: web::Data<AppState>) -> impl Responder {
    // not using this *yet*
    let query_string = Query::<QueryParams>::from_query(req.query_string()).unwrap();
    tracing::debug!("Query string is {:?}", query_string);

    match state.collection.find(doc! { "HQ State": "OR" }, None).await {
        Ok(cursor) => match cursor.try_collect::<Vec<FireStation>>().await {
            Ok(stations) => {
                println!("{:?}", stations)
            }
            Err(e) => {
                tracing::error!("Couldn't collect stations {:?}", e)
            }
        },
        Err(e) => {
            tracing::error!("Couldn't get stations! {:?}", e)
        }
    }

    HttpResponse::Ok().json({})
}

My understanding is that the above code is querying the collection for anything that "HQ State" value of "OR", trying to ake a collection out of it, the printing it. But every time, I see that [] is what gets printed in the terminal.

Have I set something up wrong? Some bad db or collection configuration? Am I using collection.find wrong? Or processing the results incorrectly? Rust is still new to me.

For reference, here's a picture of my Atlas collection I am trying to reach:

enter image description here

0

There are 0 best solutions below