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"