Ahmed Haque
Ahmed Haque

Reputation: 7544

Query For All Array Matches in Mongoose

I have a feeling this may have been asked elsewhere, but am having a tough time finding an answer.

Basically, I have a MongoDB/Mongoose Schema that stores a list of registered users. I am building a GUI that can query for all records that meet certain conditions. In this case, I am wanting to let the GUI users select via checkboxes all the genders they'd like to include in the query.

If I were passing in just a string, I know I'd write it as follows:

    User.find({"gender": gender}).exec(function(err, users){
        if(err)
          res.send(err);
        res.json(users);
    });

But since I'll possibly be passing in an array of options, is there a native Mongoose function I can use to query the following cases?

[Male]
[Male, Female, Other]
[Male, Other]
[Female]
etc.

What would be the best way to write this query in Mongoose?

Thanks!

Upvotes: 1

Views: 598

Answers (1)

Alireza Davoodi
Alireza Davoodi

Reputation: 769

You should use $in operator

  var gender = [Male, Female, Other]
  User.find({"gender": {$in: gender}})

Upvotes: 7

Related Questions