This is the code:
usermodel.findOne({ user: req.session.user }, function (err, usr){
following = [];
for (var i = 0; i < usr.follow.length; i++) {
usermodel.findOne({ _id: usr.follow[i] }, function (err, followed){
if (err) throw err;
following.push(followed);
});
}
if (err) throw err;
console.log(following);
res.render('home.ejs', {
user: usr,
following: following
});
});
I'm trying to push all the usermodel.find into the array following. Inside the loop for, if I use console.log(following), the console would show me the array with all the mongoose findresults, but the problem is that, outside the forloop, the array following is empty! It's weird, and I don't know exactly what to do. Any solutions for this...?
Thank's advance!
The problem is that you are calling async functions, which get executed sometime in the future, but you are expecting following to contain items in the present.
Your application should be restructured like this:
usermodel.findOne({ user: req.session.user }, function (err, usr){
following = [];
// i assume that usr.follow is an array
usermodel.find({ _id: { $in: usr.follow } }, function (err, userList){
if (err) throw err;
console.log(userList);
res.render('home.ejs', {
user: usr,
following: userList
});
});