Bulding an API with node.js/express and mongoDB. I have two collections with like a many to many relation, Users and Items. I want to get all the Items that the User are following. The users Items is an array with ids referring to Items.
How do i query so i get all the Items thats in the useritems array?
Collections:
Users:
{
email: "[email protected]",
username: "johnny",
useritems: ["51e101df2914931e7f000003", "51cd42ba9007d30000000001"]
}
Items:
{
"name": "myitem",
"description": "Description of item"
"_id": "51e101df2914931e7f000003"
}
{
"name": "myitem2",
"description": "Description of item2"
"_id": "51cd42ba9007d30000000001"
}
{
"name": "myitem3",
"description": "Description of item3"
"_id": "51e101df2914931e7f000005"
}
EDIT:
I updated the code. I now get the array of useritems ids based on the user id. Problem is when i try to send the items to array. Items is always empty. Is something wrong with my query?
exports.findItemsByUserId = function(req, res) {
//var id = req.params.id;
var userId = "51e6a1116074a10c9c000007"; //Just for testing
db.collection('users', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(userId)}, function(err, user) {
db.collection('items', function(err, collection) {
console.log("user undefined? ",user);
console.log("useritems ",user.useritems);
collection.find({'_id': {'$in' : user.useritems}}).toArray(function(err, items) {
console.log("useritems ",user.useritems); // <--Gets me array with the ids
console.log("items ", items); //<--Empty
res.send(items);//Empty
});
});
});
});
};