Get objects in a collection with an array of id's in mongoDB
12,597
Solution 1
Problem solved. Not the most fancy solution but it works. Just looping through some arrays. Guess there's some proper query for this.
exports.findItemsByUserId = function(req, res) {
var id = req.params.id; //<--- was disabled, it will give an error when testing this code.
var userId = "51e6a1116074a10c9c000007"; //Just for testing
db.collection('users', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, user) {
db.collection('items', function(err, collection) {
var itemsArray = []
var itemIds = user.useritems
for (var i = 0; i < itemIds.length; i++) {
itemIds[i]
collection.findOne({'_id':new BSON.ObjectID(itemIds[i])}, function(err, item) {
itemsArray.push(item);
if(itemIds.length === itemsArray.length){
res.send(itemsArray);
}
});
};
});
});
});
};
Solution 2
Maybe this is more like it?
exports.findItemsByUserId = function(req, res) {
var userId = "51e101df2914931e7f000003"; //Just for testing
var user = db.users.find({"_id": userId});
var items = db.items.find({'_id': {'$in' : user.useritems}});
res.send(items.toArray());
};
Related videos on Youtube
Author by
Bullfinch
Updated on September 14, 2022Comments
-
Bullfinch over 1 year
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 }); }); }); }); };