3

I tried to implement mongodb with actix web. This is my main class:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let db_helper = DbHelper::open_connection().await?;
    println!("Connected!");
     Ok(())
}

// my db helper
pub async fn open_connection() -> std::io::Result<DbHelper> {
    let client = Client::with_uri_str("mongodb://localhost:27017/").await.expect("connect to mongodb issue!");
    // List the names of the databases in that deployment.
    let databases = client.list_database_names(None, None).await.expect("Test error");
    for mongodb in databases {
        println!("{}", mongodb);
    }
    let database = client.database(DB_NAME);
    let db_helper = DbHelper {
        client,
        database,
    };
    Ok(db_helper)
}

When I tried to run this code, it gave me an error:

thread 'main' panicked at 'there is no reactor running, must be called from the context of a Tokio 1.x runtime',

The problem is from this line: let databases = client.list_database_names(None, None).await.expect("Test error");. I don't know what happened here. If I remove that line or replace actix_web::main with #[tokio::main], it can work. However, the actix web cannot work.

actix-web = "3"
mongodb = "2.0.0-beta.2"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86

1 Answers1

4

The problem is that you are using Actix web 3.x with Tokio 1.x and mongoDB client 2.x. You need to use Actix web 4.x for it to work with the other two.

moy2010
  • 854
  • 12
  • 18