Reputation: 65
Struggling with a query, I have a collection of users:
{
"_id": "5c87bda25fdaasdf00171001e1",
"name": "UserTwo Name",
"email": "[email protected]"
},{
"_id": "5c87bda25fda8b00171001e1",
"name": "User Name",
"email": "[email protected]"
}
I also have an array of objects containing a _userId key. I need to get all users where the _id of the user equals the value of _userId in my array.
[
{_userId: "5c87bda25fda8b00171001e1"},
{_userId: "5c87bda25fdaasdf00171001e1"},
]
What I have so far is:
User.find(
{
_id: { $in: req.body.users }
}
)
Which should be fine if req.body.users was just an array of ids, not array of objects.
Any help would be greatly appreciated. Thanks,
Upvotes: 1
Views: 1672
Reputation: 23565
You have to turn the array
[
{_userId: "5c87bda25fda8b00171001e1"},
{_userId: "5c87bda25fdaasdf00171001e1"},
]
into
[
"5c87bda25fda8b00171001e1",
"5c87bda25fdaasdf00171001e1",
]
So how can we do that ?
Example 1 : using Array.map
which iterate through the specified array, call a function and then create a new array with values being the ones returned by the function it called.
console.log([{
_userId: "5c87bda25fda8b00171001e1",
},
{
_userId: "5c87bda25fdaasdf00171001e1",
},
].map(x => x._userId));
Example 2 : Using a well known for
loop and create the array ourselves
const arr = [{
_userId: "5c87bda25fda8b00171001e1"
}, {
_userId: "5c87bda25fdasdf0017101e1"
}, ];
const newArr = [];
for (let i = 0; i < arr.length; i += 1) {
newArr.push(arr[i]._userId);
}
console.log(newArr);
PS : As @Ivan Vasiljevic proposed, when building the array of id, you can turn the string
into ObjectID
objects. It's not mandatory to do it using mongoose.find
; it is tho using mongoose.aggregate
.
Upvotes: 0
Reputation: 5718
You should modify your query like this:
User.find({
_id: { $in: req.body.users.map(user => ObjectId(user._userId) }
});
You need to convert _userId string to ObjectId. And that will be done with map
function.
Upvotes: 5