0

This is my async function that uses rust to connect to an existing mongoDB database. Is there a way to return / export the client variable / object and make it usable in other Files / Functions?

async fn connect_to_db() -> Result<(), Box<dyn Error>> {
    // Load the MongoDB connection string from an environment variable (or string):
    let client_uri = "mongodb://localhost:27017";
    let options =
        ClientOptions::parse_with_resolver_config(&client_uri, ResolverConfig::cloudflare())
            .await?;
    let client = Client::with_options(options)?;
    let db = client.database("fiesta");

    // Select Collection(s)
    let user_col: Collection<User> = db.collection("users");
    let skills_col: Collection<Skill> = db.collection("skills");

    //ok.
    Ok(())

}

Help would be appreciated.

Dependencies:

  • rocketrs
  • mongodb
  • tokio & serde

I have tried multiple things such as changing the lifetimes and changing the return type of the function, but to no avail.

Wadafacc
  • 3
  • 2
  • 1
    I don't think the SO rust community has any psychic yet, and you're not actually showing what you attempted nor **the errors you got when it failed**, which makes debugging less than easy. According to [the documentation](https://docs.rs/mongodb/2.3.1/mongodb/struct.Client.html) the mongodb client is owned, and database instances are owned, so having a return type of `Result` and returning an `Ok(client)` should work fine. – Masklinn Oct 25 '22 at 13:21

0 Answers0