【发布时间】:2021-07-06 05:08:15
【问题描述】:
我有以下代码应该从 mongodb 返回一个文档列表。
struct Vehicle{
id: String,
name: String
}
pub async fn list_all() -> Vec<Vehicle>{
let mongodb = connection_bd::connection_mongodb().await;
let mongodb_collection = mongodb.collection("Vehicle");
let result = mongodb_collection.find(None, None).await; //result: Result<Cursor<Document>, Error>
let cursor = match result { //cursor: Cursor<Document>
Ok(x) => x,
Err(_) => return vec![]
};
//...
}
我无法完成代码,因为我不知道如何将Cursor<Document> 转换为Vec<T>,这是我第一次看到Cursor<Document>,我不知道它是什么。
更新
错误信息:
error[E0308]: mismatched types
--> src\vehicle_repo.rs:77:40
|
77 | pub async fn list_all() -> Vec<Vehicle>{
| ________________________________________^
78 | | let mongodb = connection_bd::connection_mongodb().await;
79 | | let mongodb_collection = mongodb.collection("Vehicle");
... |
84 | | };
85 | | }
| |_^ expected struct `Vec`, found `()`
|
= note: expected struct `Vec<Vehicle>`
found unit type `()`
【问题讨论】:
-
你得到的错误仅仅是因为你没有在函数结束时返回任何东西。
-
@kmdreko 如果这就是我想通过 cursor 变量返回
vec<Vehicle>的原因。