首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Rust mongodb中找到().lean()?

如何在Rust mongodb中找到().lean()?
EN

Stack Overflow用户
提问于 2022-02-11 19:23:36
回答 1查看 57关注 0票数 0

我试图使mongodb文档变得简单明了,以便应用okapi的开放api,该api不允许在struct中使用ObjectId。

但我发现这两种方法都不像

FindOptions::builder().lean().build();

nor

colleciton.find(None, None).lean().await?工作。

如何将MongoDB Document转换为JsonSchema

示例

在此之前

代码语言:javascript
复制
{
  _id: ObjectId,
  name: String
}

之后

代码语言:javascript
复制
{
  _id: String,
  name: String
}
EN

回答 1

Stack Overflow用户

发布于 2022-02-19 08:53:09

可以使用ObjectId作为基础创建自定义结构,并为该自定义结构创建实现JsonSchema。

代码语言:javascript
复制
use mongodb::bson::oid::ObjectId;
use schemars::JsonSchema;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
use schemars::gen::SchemaGenerator;
use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectID(ObjectId);

impl JsonSchema for ObjectID {
    fn schema_name() -> String {
        stringify!(String).to_owned()
    }

    fn json_schema(gen: &mut SchemaGenerator) -> Schema {
        let mut schema: SchemaObject = <String>::json_schema(gen).into();
        schema.number().minimum = Some(1.0);
        schema.into()
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct Customer {
    pub _id: ObjectID,
    pub name: String
}

fn main() {
    let c = Customer{_id: ObjectID(ObjectId::new()), name: String::from("John")};
    println!("{:?}", c);
    let serialized = serde_json::to_string(&c).unwrap();
    println!("serialized = {}", serialized);

    let deserialized: Customer = serde_json::from_str(&serialized).unwrap();
    println!("deserialized = {:?}", deserialized);
}

// Output
// Customer { _id: ObjectID(ObjectId("6210af6079e3adc888bef5af")), name: "John" }
// serialized = {"_id":{"$oid":"6210af6079e3adc888bef5af"},"name":"John"}
// deserialized = Customer { _id: ObjectID(ObjectId("6210af6079e3adc888bef5af")), name: "John" }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71085558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档