成功返回一个连接示例MongoDb-Rust

nhaq1z21  于 2022-11-12  发布在  Go
关注(0)|答案(1)|浏览(101)

我正在学习生 rust ,我一直在遵循生 rust 的书。通常,我会尝试实施一些东西来加强我的知识。
最近我在研究如何使用MongoDb create创建一个instace并返回数据库的名称。
以下是我所拥有的示例:
1.包含构建mongo连接字符串的实现的文件夹。

  1. A .env文件
    1.一个主函数来获取我需要的信息。
    mongo_连接.rs

# [derive(Debug)]

pub struct ConnectionString {
    pub username: String,
    pub password: String,
    pub cluster: String,
}

impl ConnectionString {
    pub fn build_connection_string() -> String {
        return format!("mongodb+srv://{}:{}@a{}.k1jklnx.mongodb.net/?retryWrites=true&w=majority",
        Self.username, Self.password, Self.cluster)
    }
}

main.rs

mod database;
use crate::database::mongo_connection;
use mongodb::{Client, options::ClientOptions};
use std::error::Error;
use dotenv::dotenv;
use std::env;
use tokio;

async fn create_database_connection() -> Client {
    dotenv().ok(); //Loading environment variables from .env file
    let connection_parameters = mongo_connection::ConnectionString{
        username: env::var("USERNAME").expect("No username found on .env"),
        password: env::var("PASSWORD").expect("No password found on .env"),
        cluster: env::var("CLUSTER").expect("No cluster found on .env")
    };
    let mut url: String = mongo_connection::ConnectionString::build_connection_string();
    println!("{}", url);
    let options = ClientOptions::parse(&url).await?;
    return Client::with_options(options).await;
}

# [tokio::main]

async fn main() -> Result<(), Box<dyn Error>> {
    let client = create_database_connection().await?;
    let db = client.database(&"runt");
    println!("{:?}", db.name());
    Ok(())
}

我面临的问题是我需要返回一个连接客户端。但是我一直收到错误:

let options = ClientOptions::parse(&url).await?;
    ^ cannot use the `?` operator in an async function that returns `Client`

如果我将函数的结果更改为:Result<Client, dyn Eq>,然后我得到错误:

async fn create_database_connection() -> Result<Client, dyn Eq> {
`Eq` cannot be made into an object
^^^^^^^^^^^^^^^ the trait cannot be made into an object because it uses `Self` as a type parameter
    |

如果您有任何关于如何解决错误或解决方法的建议,我们将不胜感激。

5t7ly7z5

5t7ly7z51#

可以将返回类型更改为Result<Client, mongodb::error::Error>Result<Client, Box<dyn Error>>,这两种类型都可以,但第一个版本的代码如下:

async fn create_database_connection() -> Result<Client, mongodb::error::Error> {
    dotenv().ok(); //Loading environment variables from .env file
    let connection_parameters = mongo_connection::ConnectionString{
        username: env::var("USERNAME").expect("No username found on .env"),
        password: env::var("PASSWORD").expect("No password found on .env"),
        cluster: env::var("CLUSTER").expect("No cluster found on .env")
    };
    let mut url: String = mongo_connection::ConnectionString::build_connection_string();
    println!("{}", url);
    let options = ClientOptions::parse(&url).await?;
    return Client::with_options(options).await;
}

如果要使用Box<dyn Error>版本,则返回值还需要一个.into(),以便将Client::with_options()Result<Client, mongodb::error::Error>转换为Result<Client, Box<dyn Error>>

相关问题