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);
CodePudding user response:
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);