Rust中如何将mongodb::Cursor转换为Vec?
解决MongoDB Cursor转Vec的报错问题
问题根源
mongodb::Cursor 实现的是 Stream<Item = Result<User, mongodb::error::Error>>,直接调用 .collect() 转 Vec<User> 会触发 trait 绑定错误——因为 Vec<User> 只能接收 User 类型元素,无法直接扩展 Result<User, Error> 类型。
两种可行解决方案
方案一:用TryStreamExt::try_collect(推荐)
先引入futures::TryStreamExt,它提供的try_collect方法会自动将流中所有Ok(User)收集为Vec<User>,遇到第一个Err就直接返回错误:
use futures::{StreamExt, TryStreamExt}; use mongodb::Collection; use user_model::User; async fn fetch_users(collection: &Collection<User>) -> Result<Vec<User>, mongodb::error::Error> { // 执行查询获取Cursor let cursor = collection.find(None, None).await?; // 收集结果,自动处理错误 let users = cursor.try_collect().await?; Ok(users) }
方案二:手动过滤错误(自定义处理)
如果需要跳过错误文档而非直接返回错误,可以用filter_map过滤掉Err结果,再收集Ok的User:
use futures::StreamExt; use mongodb::Collection; use user_model::User; async fn fetch_users(collection: &Collection<User>) -> Vec<User> { let cursor = collection.find(None, None).await.expect("查询执行失败"); // 过滤错误结果,仅保留有效User let users: Vec<User> = cursor .filter_map(|res| async { res.ok() }) .collect() .await; users }
关于之前尝试的说明
.try_next()仅能获取流中的单个元素,无法批量收集;而.map()若要处理Result,需要显式将Result<User, Error>转换为User(比如unwrap或?),但在Stream的同步map中无法直接使用?,异步场景下不如try_collect简洁高效。
内容的提问来源于stack exchange,提问作者CyberFlaw
相关产品推荐
相关产品推荐

