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!

Dawn17
  • 7,825
  • 16
  • 57
  • 118

2 Answers2

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

donquixote
  • 365
  • 3
  • 10
  • 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) – Dawn17 Nov 03 '17 at 00:13
  • https://stackoverflow.com/questions/14559200/how-to-exclude-one-particular-field-from-a-collection-in-mongoose 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 – donquixote Nov 03 '17 at 05:40
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
Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53