I want to build a query as per the value available in the query parameters of the URL. The sample URL is :-
http://localhost:3000/api/user?page=&status=&search&role_id=
So when the status is available, the where clause related to it should work, the same for search and role_id.
I have tried to built a query where pagination part along with search parameter is working perfectly. But when I pass/set the keys of query string, the query shows no results.
The query I have build so far is something like this:-
let {page, search, status, role_id} = req.query;
role_id = role_id ? role_id : null;
status = status ? status : null;
const currentPage = parseInt(page) || 1;
const perPage = recordsPerPage;
const userData = await User.find({
$and: [
{
$or : [
{username:{'$regex' : search, '$options' : 'i'}},
{email:{'$regex' : search, '$options' : 'i'}}
]
},
{
$or : [
{status : status}
]
},
{
$or : [
{role_id : role_id}
]
},
{
email: { $ne: '[email protected]' }
}
]
})
.sort({_id : -1})
.populate('role_id')
.skip((currentPage - 1) * perPage).limit(perPage);