Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Issue with push and mongoose results

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 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!

Problem courtesy of: MrMangado

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
    });
});
Solution courtesy of: randunel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Issue with push and mongoose results

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×