mongodbCursor Streamを実装します futuresから クレート
。これは、docs
に記載されています。 :
実際には、try_collect()を使用することをお勧めします TryStreamExtからの関数
Result<Vec<Document>>を取得するための特性 代わりは。次に、unwrap_or_else()を使用できます リストを返します。 collection_with_type()も使用する必要があります 結果がDocumentだけでなく、適切なタイプに自動的に逆シリアル化されるようにコレクションを取得するメソッド (Debugが実装されていることを確認してください 、Serialize およびDeserialize 。
これが実用的なサンプルです
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![])
}