【问题标题】:How to create an endpoint with optional parameters? (Node, Express, MongoDB)如何使用可选参数创建端点? (节点、快递、MongoDB)
【发布时间】:2021-03-24 12:58:35
【问题描述】:

我创建了一个包含两个主要实体 CATS 和 BREEDS(一对多)的 MongoDB,但我从未使用过可选参数。

我要处理以下请求。

  • 获取所有猫的“GET”请求(带有一个可选参数 确定是否也应返回描述,以及另一个可选的 按品种过滤的参数)

  • '获取特定猫的 GET 请求(带有可选参数 这将确定是否也将返回有效负载) 姓名或身份证

我包含我的数据库模式以备不时之需。

const CatSchema = new Schema({
    name: { type: String, required: true, trim: true },
    description: { type: String, required: true, trim: true },
    breed: {
        type: Schema.Types.ObjectId,
        ref: "Breed"
    }
});

const BreedSchema = new Schema({
    name: { type: String, required: true, trim: true }
});

【问题讨论】:

    标签: node.js mongodb express api-design optional-parameters


    【解决方案1】:

    使用问号使您的参数可选。 /cats/:description?

    您还可以使用多个可选参数。 /cats/:description?/:breed?

    编辑, 请务必检查参数:

    if(description) {
        //show cats with description
    } 
    

    类似的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多