使用带有凭据的URI无法连接到MongoDB

时间:2018-11-21 23:53:41

标签: mongodb rust

我正在尝试使用MongoDB Rust驱动程序构建一个简单的CRUD API,但是我无法在数据库中插入任何内容。我正在使用Mlab托管数据库。

我正在运行的代码:

#[macro_use(bson, doc)]
extern crate bson;
extern crate mongodb;

use mongodb::db::ThreadedDatabase;
use mongodb::{Client, ThreadedClient};

fn main() {
    let client = Client::with_uri(
        "mongodb://<my_db_username>:<my_db_password>@ds235711.mlab.com:35711/rustcrud",
    )
    .expect("Failed to initialize client");

    let coll = client.db("rustcrud").collection("test");

    coll.insert_one(doc! { "title": "Back to the Future" }, None)
        .unwrap();
}

还有我得到的错误:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: OperationError("not authorized on rustcrud to execute command { insert: \"test\", $db: \"rustcrud\" }")', libcore/result.rs:1009:5

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

从项目的GitHub存储库中,issue 256: Add auth to base examples

  

用户密码身份验证在数据库级别进行。用户,密码和数据库都是从URI解析的,但是我不认为我们将其设置为在创建数据库对象时自动进行身份验证

let client = Client::with_uri("mongodb://x:y@localhost:27017")?;
client.auth("x", "y");