I am a mongodb newbie and would greatly appreciate help on this problem described below.
I have two collections "users" and "bags". The user collections scheme has {username, firstname, lastname} and the bag collection schema has {username, bagname, bagimage}.
While fetching users bags, I also want to display the firstname and lastname. My problem is that I cant seem to be able to frame a query correctly. I am using nodejs and mongojs driver. Below is my query for fetching all bags
thmConfig.db.bags.find({status: "1"}).sort({$natural:-1}, function(err, data)
{
var bagList = '{"bags":[';
if( err || !data) res.send('[{"status": "0"}]');
else data.forEach( function(innerData) {
console.log(innerData.username);
bagList += JSON.stringify(innerData)+",";
/*
This is where I would lke to also append the firstname from the
users collection
*/
});
console.log(bagList.slice(0,1));
res.write(magList.slice(0,-1));
res.end(']}');
});
I would greatly appreciate any help or pointers about this. I dont have a choice about changing the driver, so I specifically want to implement this using mongojs for now.
Thanks and regards, Titash
I don't think that you have much choice other than reading from the users collection and doing this "join" operation programmatically. You can either read the user document per each bag (inside your loop), or read the entire users collection into an object in advance, and do lookups by username
You could use the $in operator for that.
Pseudo-code(ish):
// get an array of bags matching your query
db.bags.find({status: "1"}).sort({$natural:-1}, function(err, bags) {
// get a list of usernames from the bags:
var usernames = bags.map(function(bag) { return bag.username; });
// perform query on user table: find all users for which we have a bag
db.users.find({ username : { $in : usernames } }, function(err, users) {
// create a mapping of username -> first name for easy lookup
var usernames = {};
users.forEach(function(user) {
usernames[user.username] = user.firstname;
});
// map first names to bags
bags.forEach(function(bag) {
bag.firstname = usernames[bag.username];
});
// done: return it as JSON (no need to build a JSON string ourselves)
res.send({ bags : bags });
});
});