Need an example for connecting to MongoDB on Rust #1961
Unanswered
ayyagari-dalalstreet
asked this question in
Questions
Replies: 2 comments
-
@ayyagari-dalalstreet Do you need mongodb with rocket_contrib or would wither as an odm be fine? Just asking cause I could help out wither as I was using it with rocket. In case of wither: use rocket::State;
use rocket::serde::json::Json;
use rocket::serde::{Deserialize, Serialize};
use wither::bson::{doc, oid::ObjectId};
use wither::prelude::*;
use futures::stream::StreamExt;
#[cfg(debug_assertions)]
use dotenv::dotenv;
mod data {
mod entity {
#[derive(Debug, Model, Serialize, Deserialize)]
#[model(index(keys = r#"doc!{"name": 1}"#, options = r#"doc!{"unique": true}"#))]
struct Data {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
pub id: Option<ObjectId>,
pub name: String,
}
impl Data {
pub async fn sync_db(db: &wither::mongodb::Database) -> () {
Data::sync(db).await.unwrap();
}
}
}
}
pub struct MongoState {
db: wither::mongodb::Database,
}
#[get("/")]
async fn get_all_data(db: &State<MongoState>) -> Json<Vec<data::entity::Data>> {
let mut cursor = data::entity::Data::find(&db_state.db, None, None).await.unwrap();
let mut results = Vec::new();
while let Some(data_point) = cursor.next().await {
results.push(data_point);
}
return Json(results);
}
#[launch]
async fn rocket() -> _ {
#[cfg(debug_assertions)]
info!("Loading .env file if present");
#[cfg(debug_assertions)]
dotenv().ok();
let db = Client::with_uri_str(
std::env::var("MONGO_DB_URL")
.expect("Could not detect env variable MONGO_DB_URL to connect to the db")
.as_str(),
)
.await
.unwrap()
.database(
std::env::var("MONGO_DB_NAME")
.expect("Could not detect MONGO_DB_NAME to name the use database")
.as_str(),
);
// Do your index syncing if needed
data::entity::Data::sync_db(&db).await;
rocket::build().mount("/data", routes![ get_data ]).manage(MongoState{ db })
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
@ayyagari-dalalstreet I've updated your issue (#1962). Dependencies version: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have tried the methods given by the doc url[https://rocket.rs/v0.4/guide/state/#databases] and explored the drivers but getting an issue of
pbkdf2
version is unmatched.Unable to solve with the help of the current resources and findings. Need help with an small example on connecting
Rocket
withMongoDB
As a author I am new to
Rust
and my previous background was working withJS
andPython
Beta Was this translation helpful? Give feedback.
All reactions