hex20dec
hex20dec

Reputation: 127

How do I create a query from an array with mongoose?

So I have this array with 3 IDs: ["56ba576f66b9add00e4d3082","56b9252266b9add00e4d3080","56b908f166b9add00e4d307f"]

I want to build a query that says something like that:

userModel.find({ $or: 
  [ 
    {_id:"56ba576f66b9add00e4d3082"}, 
    {_id:"56ba576f66b9add00e4d3082"}, 
    {_id:"56ba576f66b9add00e4d3082"} 
  ]}, 
    {email:true});

Is there some sort of a method to use in order to produce such query with the array? Should I be using mapReduce or the $where method or anything else? (I never used those before so I'm not sure if this is the case or not)

Perhaps I'm asking the wrong question? Any recommendations are very much welcome.

Upvotes: 0

Views: 122

Answers (2)

Blakes Seven
Blakes Seven

Reputation: 50406

If you just have one element then just use $in:

var array = [
    "56ba576f66b9add00e4d3082",
    "56b9252266b9add00e4d3080",
    "56b908f166b9add00e4d307f"
];

userModel.find({ "_id": { "$in": array } }, { "email": true });

An $in condition is basically an $or applied to the same field.

Upvotes: 2

4lejandrito
4lejandrito

Reputation: 182

Try using the map function:

array = ["56ba576f66b9add00e4d3082","56b9252266b9add00e4d3080","56b908f166b9add00e4d307f"]

userModel.find({ $or: array.map(function(id) {
    return {_id: id};
})}, {email:true});

Upvotes: 0

Related Questions