我有这段代码来连接MongoDB,当我试图运行cargo run
时,代码在if语句中返回一个错误,我不知道为什么。我试着调试了好几天。这就是代码:
use std::iter::FilterMap;
use rocket::serde::json::{json, Value};
use futures::{StreamExt};
use mongodb::{bson::doc, options::ClientOptions, Client};
use bson::{Document};
use warp::body::json;
/**
* MongoDB client
*/
#[tokio::main]
pub async fn database_connection(key: &str, value: &str) -> Result<Option<Value>, mongodb::error::Error> {
// uri to connect to the database
let uri = "mongodb://admin:adminpassword@localhost:27017";
// options to connect to the database
let mut client_options =
ClientOptions::parse(uri)
.await?;
// Create a new client and connect to the server with the given options
let client = Client::with_options(client_options)?;
//Connect to the BinGo! database
let material = client.database("BinGo!");
// Search thrue a collection
let collection = material.collection::<Document>("bingo_materials");
let filter = doc! {
key: value
};
print!("Making the query to the database...\n");
println!("Filter: {:#?}", filter);
print!("-------------------------\n");
let mut cursor = collection.
find(filter, None)
.await?;
if let Some(result) = cursor.next().await {
println!("{:#?}", result);
let result_json: &Result<Document, mongodb::error::Error> = &result;
return Ok(Some(result_json));
}else{
return Ok(None);
}
}
字符串
错误如下:
error[E0308]: mismatched types
--> src/databases.rs:57:5
|
25 | pub async fn database_connection(key: &str, value: &str) -> Result<Option<Value>, mongodb::error::Error> {
| -------------------------------------------- expected `Result<std::option::Option<rocket_dyn_templates::tera::Value>, mongodb::error::Error>` because of return type
...
57 | / if let Some(result) = cursor.next().await {
58 | | println!("{:#?}", result);
59 | | let result_json: &Result<Document, mongodb::error::Error> = &result;
60 | | return Ok(Some(result_json));
61 | | }else{
62 | | return Ok(None);
63 | | }
| |_____^ expected `Result<Option<Value>, Error>`, found `Result<Option<&...>, ...>`
|
= note: expected enum `Result<std::option::Option<rocket_dyn_templates::tera::Value>, mongodb::error::Error>`
found enum `Result<std::option::Option<&Result<bson::Document, mongodb::error::Error>>, _>`
型
请你客气一点,我是新手,还在学习。
我期望返回result_json
的值,因为database_connection()
是从rocket.rs中的路由调用的。
1条答案
按热度按时间deyfvvtc1#
这里有几个提示。。
我建议您先使用
cargo add serde_json
(如果您还没有这样做的话),然后简单地将mongodb::bson::Document
转换为serde_json::Value
。下面是一个示例:字符串
您还可以添加流行的anyhow crate,并使返回类型为
anyhow::Result<Option<serde_json::Value>>
。然后你可以这样做:型