I need to make a MongoDB query and add an extra field to each one of my results. The field values depend of the result of another query.
I'm trying to call the nested query in my server.js
code. It's not working because res.json(data)
is called before data elements are modified. I suspect there's a way to do what I want using a nested query (or using something like forEach
or aggregate
) in my db.js
code, but my lack of experience with JavaScript/Mongo didn't let me to find a good solution.
Any help would be appreciated.
server.js
app.get("/get_users_list", function(req, res) {
db.getUsersByCity(req.query.city, function(err, data) {
if (err) {
res.send(err);
} else {
for(var i in data) {
var rec = data[i];
db.checkVisitation({'user_id': req.query.user_id, 'friend_id': rec.user_id},
function(inner_err, inner_data) {
if (inner_data) {
rec["visited"] = "true";
} else {
rec["visited"] = "false";
}
});
}
res.json(data);
}
});
});
db.js
var checkVisitation = function(visitJSON, callback) {
db.visitations.findOne(visitJSON, callback);
}
var getUsersByCity = function(city, callback) {
db.users.find({'city': city}).toArray(callback);
}
EDIT:
I was able to fix the problem by adding a check inside my inner callback:
if (i == data.length - 1) {
res.json(data);
}