mongodbrustrust-actix

How to use MongoDB with r2d2 and actix in rust


I am trying to make a basic web application with the rust language, using the actix framework and r2d2 with mongodb as the database. I could not find any complete and working documentation on how to archive this. Maybe someone can help me out here.

The problem is, that i can't seem to get a mongodb connection from the r2d2 connection pool. Sadly this part isnt covered in any documentation i found.

Some links i found:


This part creates the connection pool and hands it to actix.

fn main() {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();

    let manager = MongodbConnectionManager::new(
        ConnectionOptions::builder()
            .with_host("localhost", 27017)
            .with_db("mydatabase")
            .build()
    );    

    let pool = Pool::builder()
        .max_size(16)
        .build(manager)
        .unwrap();

    HttpServer::new( move || {
        App::new()
            // enable logger
            .wrap(middleware::Logger::default())
            // store db pool in app state
            .data(pool.clone())
            // register simple handler, handle all methods
            .route("/view/{id}", web::get().to(view))
    })
    .bind("127.0.0.1:8080")
    .expect("Can not bind to port 8080")
    .run()
    .unwrap();
}

This is the handler function trying to access the connection pool

fn view(req: HttpRequest, 
        pool: web::Data<Pool<MongodbConnectionManager>>) -> impl Responder {

    let id = req.match_info().get("id").unwrap_or("unknown");
    let conn = pool.get().unwrap();
    let result = conn.collections("content").findOne(None, None).unwrap();

   // HERE BE CODE ...

    format!("Requested id: {}", &id)
}

This is the error showing my problem. The conn variable doesnt seem to be a propper mongodb connection.

error[E0599]: no method named `collections` found for type `std::result::Result<r2d2::PooledConnection<r2d2_mongodb::MongodbConnectionManager>, r2d2::Error>` in the current scope  --> src\main.rs:29:23
   |
29 |     let result = conn.collections("content").findOne(None, None).unwrap();
   |   

Solution

  • 10 |     let coll = conn.collection("simulations");
       |                     ^^^^^^^^^^
       |
       = help: items from traits can only be used if the trait is in scope
       = note: the following trait is implemented but not in scope, perhaps add a `use` for it:
               `use crate::mongodb::db::ThreadedDatabase;`
    

    my compiler told me to add mongodb::db::ThreadedDatabase in scope.