Mongoose where value in array

Issue

I have the below code to return all blogs where the blog author ID is equal to the ID of the first administrator (orgAdmin) in an array:

let officialBlogs = await Blog.find().where('author.id').equals(help.orgAdmins[0]);

But I can’t work out how to adapt this code so I can return blogs where the author matches ANY of the administrators in the array (i.e. orgAdmin[0], orgAdmin[1], orgAdmin[2] etc. Can anyone please advise?

Solution

You can use $in operator to get things based on passed ids like this:

const ids = [];
help.orgAdmins.forEach(id => ids.push(id));

let officialBlogs = await Blog.find({author.id: { $in: ids }});

Answered By – Apoorva Chikara

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.