2

I am new to RESTful APIs and I've successfully implemented the GET and DELETE command for my API (GET localhost:4000/api, DELETE localhost:4000/api on Postman works fine).

Code for my get looks like:

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

Now I want to implement using parameters. For example, I want to implement something like sorting where

http://localhost/4000/api/users?sort={"name": 1} (1- ascending; -1 - descending)

would mean sorting the name in ascending order.

What I am not sure how to do is:

  1. How do I make the ?sort thing work?

  2. How do I select which field to sort?

Please help!

2 Answers 2

2

You can only pass order(asc, desc), if you want to sort by name you can do like that http://localhost/4000/api/users?order=-1 or http://localhost/4000/api/users?&order=1

then in your controller

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

});

These works if you use mongoose.js for mongodb

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

2 Comments

Thanks a lot! This helped. Could you also give me an idea of how to return a list of the data including the 'name' field? e.g. localhost:4000/api/users?select={"name": 1} (1 for include and 0 for exclude)
stackoverflow.com/questions/14559200/… this is how to exclude field in database call. localhost:4000/api/users?exclude=-1 pass parameter like that and grab from req.query.exclude. Then pass it through the mongoose
1

One cool solution that I frequently use is the following form

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

I use | for multiple fields sorting, and - for desc, + for asc

In express:

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

Comments

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.