0

I'm trying to write a simple API using filter to get users from database. I want to filter this data by given specific params, which are optional:

How to make it flexible to get data from database by querying API with no params, single param and multiple params ?

Controller:-

Method-1

const articles = await userTable.find({
    '$or': [{
        'name': req.query.name
     },
     {
       'address': req.query.address
     },
     {
       'address': req.query.address,
       'name': req.query.name
     }]
  });

When I hit by single params it give correct response but when hit by multiple params http://localhost:4000/api/filter?name=abhishek&address=tejaji it give wrong response but i want only that row which contains name abhishek and adress tejaji

Method-2

const articles = await userTable.find({
    name:req.query.name,address:req.query.address,
    $or: [ { name:req.query.name }, {address:req.query.address } ]
});

When i hit by single params it give 0 response but when hit by multiple params http://localhost:4000/api/filter?name=abhishek&address=tejaji it give correct response but i want result from single params also

Method-3

const articles = await userTable.find({
  'usertables': {
        $elemMatch: {
          'name': req.query.name,
          'address': req.query.address
        }
    }
});

When i hit by single params http://localhost:4000/api/filter?name=abhishek or multiple http://localhost:4000/api/filter?name=abhishek&address=tejaji it always give all rows from table, which is wrong.

Route:-

router.get("/filter", userController.filterMethod);

1 Answer 1

4

Try to use a filter object and add keys to it based on what params are present:

const { name, address } = req.query;
const filter = {}
if (name) {
    filter.name = name 
}
if (address) {
    filter.address = address
}
const articles = await userTable.find(filter);
Sign up to request clarification or add additional context in comments.

1 Comment

You are a genius sir, thank you so much. but i want to know apart from this solution, is there any other way ?

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.