【发布时间】:2022-01-14 14:40:08
【问题描述】:
我对 Rust 很陌生,只是在使用 MongoDB 编写 GraphQL API 时尝试学习它。目前,我正在努力将文档解码到我的 CourseDocument 结构中。
#[derive(Serialize, Deserialize, Debug, Eq)]
struct CourseDocument {
#[serde(rename = "_id")]
id: ObjectId,
#[serde(rename = "localizedFields")]
localized_fields: Vec<CourseDocumentLocalizedFields>,
categories: Vec<ObjectId>,
tags: Vec<ObjectId>,
trainers: Vec<ObjectId>,
videos: Vec<ObjectId>,
}
impl PartialEq for CourseDocument {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
在我的main() 函数中,我尝试了以下操作
let course_collection = database.collection::<CourseDocument>("courses");
let projection = doc! {"localizedFields": 1};
let options = FindOptions::builder()
.limit(10)
.projection(projection)
.build();
let mut cursor = course_collection.find(None, options).await.unwrap();
while let Some(course) = cursor.try_next().await.unwrap() {
println!("{:#?}", course)
}
此代码引发以下错误:
Error { kind: InvalidResponse { message: "missing field 'categories'" }, labels: {} }
该错误确实有意义,因为CourseDocument 要求categories 字段至少是一个空向量。但我仍然想知道正确的struct 声明是什么。
我是否必须用 Option 枚举来包装每个字段才能使投影和键入的文档成为可能?
【问题讨论】: