如何为RESTful API实现查询字符串参数

时间:2017-11-02 07:51:00

标签: node.js rest sorting

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

我获得的代码如下:

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. 如何使?排序工作?

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

  3. 请帮忙!

2 个答案:

答案 0 :(得分:2)

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

然后在您的控制器中

router.get('/', function(req, res) {
  let order = req.qeury.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

,则可以使用这些功能

答案 1 :(得分:1)

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

  

/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