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?
The
r2d2-mongodbis outdated and no longer supported, ther2d2crate marks it as:So I recommend you don't use it. You should be able to use a
mongodb::Clientormongodb::Databaseinstead of aPool<MongodbConnectionManager>.The reason for the error is the
r2d2-mongodbuses an older version ofmongodb(0.3) and therefore an older version ofbson(0.13) that is incompatible with the version ofbsonyou're using (1.1.0). You'll probably have similar compatibility issues with themongodbcrate itself as well. You can fix it by lowering your dependencies:Though, as I brought up before, I don't recommend it.