Skip to content

Instantly share code, notes, and snippets.

@ilantoren
Last active November 16, 2021 09:45
Show Gist options
  • Save ilantoren/e023f1c99958d051a28f08fe8ce03eba to your computer and use it in GitHub Desktop.
Save ilantoren/e023f1c99958d051a28f08fe8ce03eba to your computer and use it in GitHub Desktop.
Creating and using a mongodb Client
/** This is not compiler ready
from cargo.toml:
dependencies.mongodb]
version = "2.0.0"
default-features = false
features = ["sync"]
**/
use mongodb::{bson::Bson, bson::doc, bson::Document, options::ClientOptions, options::FindOptions, sync::Client, sync::Collection};
use mongodb::options::AggregateOptions;
use rocket::fairing::{AdHoc};
/**
fn init() - Establish a persistent connection to the database
note that the password to the mongodb atlas account is passed in from the environment
For this project the synchronous mongodb driver is used. This is because init() is called by stage which can not be an
async function. The connection to mongodb with the async driver has to be called from an async function
**/
fn init() -> Option<Client> {
let pwd: &'static str = env!("PWD");
let connect_string = format!("{}{}{}", "mongodb+srv://rust:", pwd, "@mflix.beal2.mongodb.net/sample_restaurants?retryWrites=true&w=majority");
let mut client_options =
ClientOptions::parse(&connect_string).unwrap();
// Manually set an option
let duration: Duration = Duration::new(60, 0);
client_options.app_name = Some("Rust Demo".to_string());
client_options.connect_timeout = Some(duration);
// Get a handle to the cluster
let client: Result<Client, mongodb::error::Error> = Client::with_options(client_options);
match client {
Ok(my_client) =>{
let ping = my_client
.database("admin")
.run_command(doc! {"ping": 1}, None).unwrap();
println!( "{}", ping);
Some(my_client)
},
Err(_) => Option::None
}
}
/**
Think of stage as your entry point.
The function can not be async and this is where you define your routes (end-points)
**/
pub fn stage() -> AdHoc {
println!("{}", "loading mongo");
let client = init().unwrap();
let mbox = Box::new( client );
AdHoc::on_ignite("mongodb", |rocket| async {
rocket.manage( mbox ).mount("/mongo", routes![neighborhoods, restaurants,restaurants_docs, cuisines])
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment