简体   繁体   English

为我的Restful API实现排序

[英]Implementing sorting for my Restful API

I've successfully implemented the GET and DELETE methods for my API (GET localhost:4000/users/api, DELETE localhost:4000/users/api on Postman works fine). 我已经为我的API成功实现了GET和DELETE方法(Postman上的GET localhost:4000 / users / api,DELETE localhost:4000 / users / api可以正常工作)。

What I want to implement now is to specify the order in which to sort each specific field where 1 is ascending and -1 is descending. 我现在要实现的是指定对每个特定字段进行排序的顺序,其中1递增,-1递减。 For example, 例如,

If I do localhost:4000/api/users?sort = { fieldName : 1 } 如果我执行localhost:4000 / api / users?sort = {fieldName:1}

This will return a list of users sorted by 'fieldName'. 这将返回按“ fieldName”排序的用户列表。

What I have done so far is : 到目前为止,我所做的是:

router.get('/', function(req, res) {
  let obj = JSON.parse(req.query.sort)

  user
   .find({})
   .sort(obj) 
   .exec(function(err, users) {
      if(err){
          res.status(404).send({
              message: err,
              data: []
          });
      } else {
          res.status(200).send({
              message: 'OK',
              data: users
          });
      }
  });
});

This works for normal sorting, but I want to know how to specify ascending and descending with -1 and 1. 这适用于常规排序,但是我想知道如何用-1和1指定升序和降序。

EDIT: 编辑:

router.get('/', function(req, res) {

    var count = req.query.count;
    var sorting = req.query.sort;
    //let obj = JSON.parse(sorting)
    let obj = {}
    obj[fieldname] = req.query.sort.fieldName == '1' ? 1:-1

    if(sorting != null) {
      user
       .find({})
       .sort(obj) 
       .exec(function(err, users) {
          if(err){
              res.status(404).send({
                  message: err,
                  data: []
              });
          } else {
              res.status(200).send({
                  message: 'OK sorted',
                  data: users
              });
          }
      });
    }

});

you must change 1 and -1 from string to number. 您必须将1和-1从字符串更改为数字。 you can get query like this "localhost:4000/api/users?sort[fieldName ] = 1" then in code define obj like 您可以得到这样的查询“ localhost:4000 / api / users?sort [fieldName] = 1”,然后在代码中定义obj这样

let obj = {}
obj['fieldName'] = req.query.sort.fieldName == '1' ? 1:-1

then pass obj for sort section in find. 然后将obj传递给find中的sort部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM