mongodbrustactix-webr2d2

How to save a document in MongoDB by r2d2 and actix?


I am new to Rust and was trying to create a webserver with Actix-web to perform CRUD operations via MongoDB. The first API I am creating is to save a simple document in MongoDB by something received from a POST request. The code for the post request handler function is:

extern crate r2d2;
extern crate r2d2_mongodb;

use r2d2::Pool;
use r2d2_mongodb::mongodb::db::ThreadedDatabase;
use r2d2_mongodb::{ConnectionOptions, MongodbConnectionManager};

use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use bson::{doc, Bson, Document};

async fn post_request(info: web::Json<Info>, pool: web::Data<Pool<MongodbConnectionManager>>) -> HttpResponse {
    let name: &str = &info.name;
    let connection = pool.get().unwrap();
    let doc = doc! {
      "name": name
    };
    let result = connection.collection("user").insert_one(doc, None);
    HttpResponse::Ok().body(format!("username: {}", info.name))
}

I am using r2d2 to establish a connection pool for MongoDB instead of opening and closing a connection. The error i am getting is

error[E0308]: mismatched types
  --> src/main.rs:17:59
   |
17 |     let result = connection.collection("user").insert_one(doc, None);
   |                                                           ^^^ expected struct `OrderedDocument`, found struct `bson::Document`

The insert_one function doc says it accepts a bson::Document but when I give that to it, it says expected struct `r2d2_mongodb::mongodb::ordered::OrderedDocument`

Here are my Cargo.toml dependancies

mongodb = "1.1.1"
actix-web = "3.3.2"
dotenv = "0.15.0"
r2d2-mongodb = "0.2.2"
r2d2 = "0.8.9"
serde = "1.0.118"
bson = "1.1.0"

How can I correct this?


Solution

  • The r2d2-mongodb is outdated and no longer supported, the r2d2 crate marks it as:

    deprecated: official driver handles pooling internally

    So I recommend you don't use it. You should be able to use a mongodb::Client or mongodb::Database instead of a Pool<MongodbConnectionManager>.


    The reason for the error is the r2d2-mongodb uses an older version of mongodb (0.3) and therefore an older version of bson (0.13) that is incompatible with the version of bson you're using (1.1.0). You'll probably have similar compatibility issues with the mongodb crate itself as well. You can fix it by lowering your dependencies:

    mongodb = "0.3.0"
    bson = "0.13.0"
    

    Though, as I brought up before, I don't recommend it.