Issue with push and mongoose results
Problem
This is the code:
usermodel.findOne({ user: req.session.user }, function (err, usr){
following = [];
for (var i = 0; i
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 find
results, but the problem is that, outside the for
loop, the array following
is empty! It's weird, and I don't know exactly what to do. Any solutions for this...?
Thank's advance!
Solution
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
});
});
Discussion
View additional discussion.