I am querying my mongodb for the user's email that is being passed through a session. When that email is found it looks for that user's friends, and those friends are supposed to be passed to the usersFriends
array which is then sent in the chunk to the browser. I included all the code in this block even though the transaction block isn't really pertinent or so I think.
The Problem: is that the usersFriends
array is outputting an empty array everywhere except when the console.log
is inside the for
loop. Thoughts?
app.get('/api/chunk', function(req, res){
var last5;
var usersFriends = [];
Transaction.find().sort({$natural:-1}).limit(5).exec(function(err, docs){
if (err) {
console.log(err);
} else {
last5 = docs;
}
});
User.findOne({ email: req.user.email }, function(err, user){
if (!user) {
console.log(err);
} else {
for (var i = 0; i < user.friends.length; i++) {
(function(cntr){
User.findOne({ email: user.friends[cntr].email}, function(err, result) {
result.password = "Sneaky sneaky"
var name = result.firstName + " " + result.lastName;
usersFriends.push({
name: name,
index: cntr
});
});
})(i);
var chunk = {
"friends": usersFriends,
"transactions": last5
};
} }console.log(usersFriends); // empty array
});
});