【问题标题】:What is the best way to handle querystrings in an express api?在 express api 中处理查询字符串的最佳方法是什么?
【发布时间】:2019-03-02 00:07:57
【问题描述】:

我是一名初学者 nodejs 开发人员,致力于开发一个带有可选查询参数的 express rest api。

例如,考虑以下用户架构:

phone: {
  countryCode: String,
  number: phoneType
},
phoneVerified: { type: Boolean, default: false },
emailVerified: { type: Boolean, default: false },
rating: Number,
balance: { type: Number, default: 0 },
occupation: String,
gender: { type: String, enum: genders },

我想在 /users 上公开这个资源并允许通过可选的查询字符串进行查询。

例如,/users?emailVerified=true&phoneverified=false&gender=male&occupation=plumber&limit=10

这应该返回所有满足条件的用户,同时保持几乎所有选项都是可选的。

以可维护和面向未来的方式做到这一点的最佳方法是什么?

方法 1:我的第一种方法是使用 if 块来检查查询中存在哪些参数并相应地构建 mongoose 查询,但这看起来很难看且很难阅读。

queryObj = {};
if (req.query.occupation) {
  queryObject = {
    ...queryObject,
    occupation: req.query.occuption
  };
}
if (req.query.phoneVerified) {
  queryObject = {
    ...queryObject,
    phoneVerified: req.query.phoneVerifed
  };
}
const users = await User.find(queryObject);

我还发现了看起来很有希望的querymen package。如果有人有经验可以指导我什么是最佳做法?提前致谢

【问题讨论】:

    标签: node.js rest api express mongoose


    【解决方案1】:

    你以正确的方式做这件事。你也可以试试

    queryObject = {};
    if (req.query.params.occupation) {
        queryObject.occupation= req.params.occuption
    }
    if (req.params.phoneVerified) {
        queryObject.phoneVerified= req.params.phoneVerifed
    }
    const users = await User.find(queryObject);
    

    您可以使用“.”向 json 添加新属性。

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      相关资源
      最近更新 更多