mongo_data/config/
mod.rs

1use crate::document::document::BaseDocument;
2use mongodb::options::{ClientOptions, CreateIndexOptions};
3use mongodb::{Client, Collection, Database, IndexModel};
4use std::error::Error;
5
6/// Get a database client by providing a database connection string
7pub async fn db_client(client_uri: String) -> Result<Client, Box<dyn Error>> {
8    let options = ClientOptions::parse(&client_uri).await?;
9
10    let client = Client::with_options(options)?;
11    Ok(client)
12}
13
14/// Get a database instance by providing a database connection string and the database name
15pub async fn init_db(client_uri: String, database_name: &str) -> Result<Database, Box<dyn Error>> {
16    let client = db_client(client_uri)
17        .await
18        .expect("could not connect to database");
19
20    let database = client.database(database_name);
21    Ok(database)
22}
23
24/// Utility function to create indexes by providing the collection, the indexes to be created and whatever index options you need.
25pub async fn create_indexes<T: BaseDocument>(
26    collection: Collection<T>,
27    indexes: Vec<IndexModel>,
28    options: Option<CreateIndexOptions>,
29) {
30    match collection.create_indexes(indexes, options).await {
31        Ok(index) => println!("{:?}", index.index_names),
32        Err(e) => println!("{:?}", e),
33    }
34}