I am trying to connect to Mongo DB from rust. I am following the tutorial here.
But I am getting the below error. I did run rustup update
and I have the latest 1.59 version.
error[E0282]: type annotations needed for `mongodb::Collection<T>`
--> src/main.rs:27:46
|
27 | let movies = client.database("sample_mflix").collection("movies");
| ------ ^^^^^^^^^^ cannot infer type for type parameter `T` declared on the associated function `collection`
| |
| consider giving `movies` the explicit type `mongodb::Collection<T>`, where the type parameter `T` is specified
For more information about this error, try `rustc --explain E0282`.
error: could not compile `try-mongo` due to previous error
Below is the code I have written.
use mongodb::{Client, options::{ClientOptions, ResolverConfig}};
use std::env;
use std::error::Error;
use tokio;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Load the MongoDB connection string from an environment variable:
let client_uri =
env::var("MONGODB_URI").expect("You must set the MONGODB_URI environment var!");
// A Client is needed to connect to MongoDB:
// An extra line of code to work around a DNS issue on Windows:
let options =
ClientOptions::parse_with_resolver_config(&client_uri, ResolverConfig::cloudflare())
.await?;
let client = Client::with_options(options)?;
// Print the databases in our MongoDB cluster:
println!("Databases:");
for name in client.list_database_names(None, None).await? {
println!("- {}", name);
}
// Get the 'movies' collection from the 'sample_mflix' database:
let movies = client.database("sample_mflix").collection("movies");
Ok(())
}
In Cargo.toml
I have the below dependecies added -
[package]
name = "try-mongo"
version = "0.1.0"
edition = "2021"
[dependencies]
mongodb = "2.1"
bson = { version = "2", features = ["chrono-0_4"] } # Needed for using chrono datetime in doc
tokio = "1"
chrono = "0.4" # Used for setting DateTimes
serde = "1" # Used in the Map Data into Structs section`
CodePudding user response:
Did you try specifying the type let movies: mongodb::Collection<_>?
CodePudding user response:
So the solution to this is to specify the mongodb::bson::Document
type to the collection
function call. Like below -
let movies = client.database("sample_mflix").collection::<Document>("movies");