I'm trying to write a simple API to get products from database. I want to filter this data by given specific params, which are optional:
router.get('/articles/:type?/:year?/:model?', api_controller.articles);
My controller looks like this:
exports.articles = async (req, res, next) => {
const articles = await Article.find({
'models': {
$elemMatch: {
'year': req.params.year,
'category': req.params.type,
'name': req.params.model,
}
}
});
res.send(articles);
}
However this works only for URL with 3 params. How to flexible get data from database by querying API with no params, single param and multiple params?