添加Vec<Rc>字段后mongodb::Cursor<Item>调用try_next报错求助
MongoDB加载含Rc字段模型的编译错误解决
问题背景
在将MongoDB数据加载到自定义Rust模型时,原本正常的代码在为Item结构体添加标记#[serde(skip)]的Vec<Rc<Relation>>类型字段后,出现编译错误:
try_next().await? { ^^^^^^^^ method cannot be called on `mongodb::Cursor<Item>` due to unsatisfied trait bounds
次要错误提示:
pub struct Cursor<T> { | -------------------- | | | doesn't satisfy `mongodb::Cursor<Item>: TryStreamExt` | doesn't satisfy `mongodb::Cursor<Item>: TryStream`
模型定义:
#[derive(Debug, Serialize, Deserialize)] pub struct Relation { #[serde(rename = "_id")] pub id: oid::ObjectId, // .... } #[derive(Debug, Serialize, Deserialize)] pub struct Item { #[serde(rename = "_id")] pub id: oid::ObjectId, pub project_id: oid::ObjectId, #[serde(skip)] pub out_relations: Vec<Rc<Relation>>, #[serde(skip)] pub in_relations: Vec<Rc<Relation>>, }
数据读取代码:
//some db init code let items = db.collection::<Item>("items"); let mut cursor = items.find(Some(doc! { "project_id": pid }), None).await?; while let Some(item) = cursor.try_next().await? { item_map.insert(item.id, item); }
问题分析
你提到的两个猜测都不准确:
- Rc未实现流特性是错误的表象,真正原因是
Item类型不满足MongoDB Cursor所需的反序列化约束; - Serde的
#[serde(skip)]标记是生效的,问题出在Serde默认未启用对Rc/Arc智能指针的序列化支持,导致Rc<Relation>无法自动实现Serialize和Deserializetrait,进而影响Item的trait实现,最终导致Cursor无法满足TryStream相关约束。
解决方案
1. 启用Serde的rc特性
在项目的Cargo.toml中,为serde依赖添加rc特性,开启对Rc智能指针的序列化支持:
serde = { version = "1.0", features = ["derive", "rc"] }
2. 确保Relation满足必要约束
如果Relation结构体没有实现Default,可以添加该derive(虽然当前Vec字段默认是空值无需此步骤,但能避免后续可能的初始化问题):
#[derive(Debug, Serialize, Deserialize, Default)] pub struct Relation { #[serde(rename = "_id")] pub id: oid::ObjectId, // 其他字段... }
3. 验证依赖版本兼容性
确保mongodb驱动版本与serde版本兼容(例如mongodb 2.x系列对应serde 1.x系列),避免因版本不匹配导致的隐性问题。
内容的提问来源于stack exchange,提问作者Yuri Gor
相关产品推荐
相关产品推荐

