Home > database >  How to get all the matching values from '$in' operator in mongoose
How to get all the matching values from '$in' operator in mongoose

Time:09-16

I have multiple checkboxes for different categories of blogs -

enter image description here

And what i want to achieve is that when i select some categories and click on filter , the specified selected blogs would be shown.I used query string parameters or url parameters to send all the selected checkbox values to the nodejs backend -

query is an array containing all the selected categories

const response = await axios.get(`http://localhost:8000/blog/all?categories=${query}`)

And in the backend -

const cat = req.query.categories;

const all = await blogModel.find({ category: { $in: cat } });

i am passing the cat , which again consists of all the selected categories from the frontend , to $in to find all the matching blogs.

But the issue i am facing is that i am not getting matching blogs , say when i select 'Science' checkbox and click on filter i am able to get all the blogs having 'Science' as a category.But when i select say 'Science' & 'Food' , i am getting an empty array as output even though i do have blogs of both categories in my mongoDB.

Backend console log of cat when i select 'Science' category -

enter image description here

And when i select 'Science' & 'Food' -

enter image description here

i get an empty array as output instead of all the blogs of 'Science' & 'Food' categories.

I am sure i am missing out something but dont know what to google to get correct results.I also went through similar stackoverflow questions but i was not able to wrap my head around on what needs to be done.I am building a simple blog website for my portfolio & thought of adding this 'filter by category' feature so that i would get to learn on how to filter values from mongodb using mongoose.Please help me resolve this issue.Thank You.

CodePudding user response:

Yes there seems no issue in your query, make sure you are passing right data to backend like you saved "food" as category in database and searching for "Food" it will return empty array as it is case sensitive. db.Posts.find({category: { $in:["Food","Gaming"]}}) You can also try this way to fetch db.Posts.aggregate([{$match:{category: {$in:["cat","dog"]}}}])

CodePudding user response:

I think you didnt path data as array to mongo query first split by , and then pass to query

const cat = req.query.categories;
cat = cat.split(",")
const all = await blogModel.find({ category: { $in: cat } });
  • Related