0

I am making a simple task app using Nodejs. When the user enters the home page, I will send the user's tasks to the front end. Each "User" has an array of task ids to sort out which task is theirs. I just keep getting an empty array when I try to push each task out to the local array.

User.findById(req.session.passport.user, function(err, user){

  if(err){
    console.log(err);
    res.redirect("/login");

  } else {

    var tasks = new Array(user.tasks.length);

    for(var i = 0; i < user.tasks.length; i++){

      Task.findById( user.tasks[i] , function(err, task){
        if(err){
          console.log(err);
        }
        if(!tasks){
          console.log("Couldn't find the task: " + user.tasks[i] );
        } else {
          console.log("Found task: " + task); //Tasks are always found
          tasks.push(task); //<=== Not pushing?
        }

      });
    }
    console.log(tasks); // <====this is alwayse EMPTY
    res.render("app-mobile", {user: user, tasks: tasks});

  }

});
Ben Steffan
  • 1,095
  • 12
  • 16
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mikey Apr 23 '17 at 17:05

1 Answers1

0

You seem to be trying to find all tasks given an array of IDs. You can simply do

Task.find({ _id: { $in: user.tasks }}, function (err, tasks) {
    if (err) {
        console.log(err);
    }
    if (!tasks){
        console.log("Couldn't find the tasks");
    }
    console.log(tasks);
    res.render("app-mobile", { user: user, tasks: tasks});
});
Mikey
  • 6,728
  • 4
  • 22
  • 45