【问题标题】:How to use MongoDB with r2d2 and actix in rust如何在 rust 中将 MongoDB 与 r2d2 和 actix 一起使用
【发布时间】:2019-12-13 18:51:47
【问题描述】:

我正在尝试用 rust 语言,使用 actix 框架和 r2d2mongodb 作为数据库。我找不到任何关于如何存档的完整且有效的文档。也许有人可以在这里帮助我。

问题是,我似乎无法从 r2d2 连接池获得 mongodb 连接。遗憾的是,我找到的任何文档都没有涵盖这部分。

我找到的一些链接:


这部分创建连接池并将其交给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();
}

这是试图访问连接池的处理函数

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)
}

这是显示我的问题的错误。 conn 变量似乎不是一个合适的 mongodb 连接。

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();
   |   

【问题讨论】:

  • 也许您只是缺少unwrap(更好:正确的错误处理)? conn.unwrap().collections...
  • No method named 'unwrap' found 没有帮助。我对生锈很陌生,我不得不承认;)。在这个 poc 工作之后,将遵循适当的错误处理和更多架构。

标签: mongodb rust rust-actix


【解决方案1】:
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;`

我的编译器告诉我在范围内添加mongodb::db::ThreadedDatabase

【讨论】:

  • 就我而言,编译器似乎已经知道coll是什么类型。可悲的是不是ThreadedDatabase,而是r2d2::PooledConnection&lt;r2d2_mongodb::MongodbConnectionManager&gt;。添加使用并没有改变这一点。
  • 添加 use mongodb::db::ThreadedDatabase 对我来说效果很好:) 我的 mongodb 更新并且想要 find_one 而不是 findOne。 @ToBe:它也是 collection 而不是 collections 让它为我工作。
  • 就是这样,tnx!
猜你喜欢
  • 2021-03-30
  • 2020-11-08
  • 2017-03-15
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 2019-05-06
  • 2014-10-21
  • 2016-07-06
相关资源
最近更新 更多