Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match all of the values specified in an array in Mongoose

so i want to run a mongoose query to find posts where all the searcharray tags are present.

The tags vary in amount.

Currently this returns posts where any of the tags are present.

Post.find({
        'tags.name': { 
            $in : searcharray
        }
    }, function(err, post) {

        console.log(post);

    }
);

I checked the docs and couldn't quite piece this one together.

Thanks

like image 387
poperob Avatar asked Oct 15 '25 14:10

poperob


1 Answers

You want $all, which is basically an $and operation with shorter syntax much as $in is an $or operation with shorter syntax:

Post.find({"tags.name": { "$all": searcharray } }, function(err, posts) {
        console.log(posts);
});

That requires that your "tags" array has members matching "name" for "all" of the items specified in the searchArray list.

As an "or" condition the $in whould just recall any documents that contained at least one of the items, so the "and" condition means all of the items.

like image 73
Blakes Seven Avatar answered Oct 18 '25 08:10

Blakes Seven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!