0

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

});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

How can I specifically make it work for query like ...?sort = { fieldName : 1 }
test it: obj[fieldName] = obj[fieldName] == '1' ? 1:-1
Can you see my EDIT? It says fieldName is not defined
well if I remove let obj it tells me that obj is not defined
change obj[fieldName] to obj['fieldName']
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.