Dawn17
Dawn17

Reputation: 8297

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).

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. For example,

If I do localhost:4000/api/users?sort = { fieldName : 1 }

This will return a list of users sorted by '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.

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
              });
          }
      });
    }

});

Upvotes: 0

Views: 2038

Answers (1)

Mahdi Hashemi
Mahdi Hashemi

Reputation: 127

you must change 1 and -1 from string to number. you can get query like this "localhost:4000/api/users?sort[fieldName ] = 1" then in code define obj like

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

then pass obj for sort section in find.

Upvotes: 1

Related Questions