【问题标题】:How to implement query string parameters for RESTful APIs如何为 RESTful API 实现查询字符串参数
【发布时间】:2018-04-14 16:08:52
【问题描述】:

我是 RESTful API 的新手,我已经成功地为我的 API 实现了 GET 和 DELETE 命令(POST 上的 GET localhost:4000/api,DELETE localhost:4000/api 工作正常)。

我的 get 代码如下:

router.get('/', function(req, res) {
    user.find({}, function(err, users) {
        if(err){
            res.status(404).send({
                message: err,
                data: []
            });
        } else {
            res.status(200).send({
                message: 'OK',
                data: users
            });
        }
    });
});

现在我想使用参数来实现。例如,我想实现排序之类的东西

http://localhost/4000/api/users?sort={"name": 1} (1- 升序;-1 - 降序)

表示按升序对名称进行排序。

我不知道该怎么做:

  1. 如何使 ?sort 工作?

  2. 如何选择要排序的字段?

请帮忙!

【问题讨论】:

    标签: node.js rest sorting


    【解决方案1】:

    你只能传递 order(asc, desc),如果你想按名字排序你可以这样做 http://localhost/4000/api/users?order=-1 要么 http://localhost/4000/api/users?&order=1

    然后在你的控制器中

    router.get('/', function(req, res) {
      let order = req.query.order;
      user
       .find({})
       .sort({"name": order}) 
       .exec(function(err, users) {
          if(err){
              res.status(404).send({
                  message: err,
                  data: []
              });
          } else {
              res.status(200).send({
                  message: 'OK',
                  data: users
              });
          }
      });
    

    });

    如果您将 mongoose.js 用于 mongodb,这些工作将有效

    【讨论】:

    • 非常感谢!这有帮助。您能否告诉我如何返回包含“名称”字段的数据列表?例如localhost:4000/api/users?select={"name": 1}(1 表示包含,0 表示排除)
    • stackoverflow.com/questions/14559200/… 这是如何在数据库调用中排除字段。 localhost:4000/api/users?exclude=-1 像这样传递参数并从 req.query.exclude 中获取。然后通过猫鼬
    【解决方案2】:

    我经常使用的一个很酷的解决方案是以下表格

    /api/users?sort=-name|+firstname

    我使用| 进行多字段排序,- 用于desc+ 用于asc

    快递:

    const { sort } = req.query; // sort = '-name|+firstname';
    const order = sort.split('|') // will return an array ['-name', '+firstname']
     .reduce((order, item) => {
       const direction = item.charAt(0) === '-' ? -1 : 1;
       const field = item.substr(1);
       order[field] = direction;
    
       return order;
    }, {})
    
    // order {'name': -1, 'firstname': 1}
    
     users.find({}).sort(order); // do your logic
    

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2015-02-02
      • 2018-04-15
      • 2010-09-15
      相关资源
      最近更新 更多