【问题标题】:MongoDB Rust: Projections with typed collections | How to do this?MongoDB Rust:类型化集合的投影|这个怎么做?
【发布时间】: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 枚举来包装每个字段才能使投影和键入的文档成为可能?

【问题讨论】:

    标签: mongodb rust graphql


    【解决方案1】:

    您可以使用clone_with_type() 来创建具有相同来源但类型不同的Collection。使用它,您可以反序列化为仅具有那些投影字段的类型。

    #[derive(Serialize, Deserialize)]
    struct ProjectedCourseDocument {
        #[serde(rename = "localizedFields")]
        localized_fields: Vec<CourseDocumentLocalizedFields>,
    }
    
    let mut cursor = course_collection
        .clone_with_type::<ProjectedCourseDocument>()
        .find(None, options)
        .await
        .unwrap();
    

    【讨论】:

    • 我是否必须为每个可能的投影都这样做,还是有更好的方法来处理这个?我到处搜索,但还没有找到好的解决方案。
    • 如果您希望结果的类型正确,我没有更好的建议。您是否仅预测 GraphQL 查询的字段?您可以按照最初的建议进行操作,并将所有字段设为可选。
    • 感谢您的帮助!我认为会有一个很好的方法来实现这一点。
    猜你喜欢
    • 2015-10-21
    • 1970-01-01
    • 2021-09-19
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2011-07-01
    • 2023-01-26
    相关资源
    最近更新 更多