Một con trỏ Cursor
triển khai Stream
từ futures
thùng
. Điều này được đề cập trong tài liệu
:
Tôi thực sự khuyên bạn nên sử dụng try_collect()
từ TryStreamExt
đặc điểm để nhận Result<Vec<Document>>
thay vì. Sau đó, bạn có thể sử dụng unwrap_or_else()
để trả lại danh sách. Bạn cũng nên sử dụng collection_with_type()
phương pháp lấy bộ sưu tập để kết quả của bạn sẽ được tự động giải mã hóa thành loại thích hợp thay vì chỉ Document
(chỉ cần đảm bảo rằng nó triển khai Debug
, Serialize
và Deserialize
).
Đây là một mẫu hoạt động
use futures::TryStreamExt;
use mongodb::Client;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Vehicle {
id: String,
name: String,
}
async fn list_all() -> Vec<Vehicle> {
let client = Client::with_uri_str("mongodb://example.com").await.unwrap();
let database = client.database("test");
let collection = database.collection_with_type::<Vehicle>("vehicles");
let cursor = match collection.find(None, None).await {
Ok(cursor) => cursor,
Err(_) => return vec![],
};
cursor.try_collect().await.unwrap_or_else(|_| vec![])
}