I am exploring next.js with mongodb, however I faced a problem that I can't find an appropriate soulution on the Internet.
I have an api handle different request. For the GET method, I want to pass different parameters(i.e. category and subcategory in this case) to apply different filters to grap data from mongodb.
Since there can be multiple subcategories, now the question is how can I properly perform the in-clause query here? I would like to perform something like
select * from post where category="music share" AND subcategoy in ("rock","metal")
It works fine when there is one subcategory only, but it will not work when there are more.
For the non working test case, current console.log returns-> query is: { category: 'music share', subcategory: 'rock,metal' }
async function getPosts(req,res){
var query={};
if (req.query.category){
query.category=req.query.category;
}
if (req.query.subcategory){
query.subcategory=req.query.subcategory;
}
try {
console.log("query is: ",query);
// connect to the database
let { db } = await connectToDatabase();
// fetch the posts
let posts = await db
.collection('posts')
.find(query)
.sort({ _id: -1 })
.toArray();
// return the posts
return res.json(JSON.parse(JSON.stringify(posts)));
} catch (error) {
// return the error
return res.json({
message: new Error(error).message,
success: false,
});
}
}