2017-04-23 13 views
0

私はNodejsを使って簡単なタスクアプリケーションを作っています。ユーザーがホームページに入ると、ユーザーのタスクをフロントエンドに送信します。各「ユーザー」には、どのタスクがタスクであるかを分類するタスクIDの配列があります。各タスクをローカル配列にプッシュしようとすると空の配列が得られます。mongooseモデルで配列を取り込む方法

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}); 

    } 

}); 
+0

可能な重複http://stackoverflow.com/questions/14220321/how-do-i-return-the-response行うことができます-from-an-asynchronous-call) – Mikey

答えて

0

IDの配列を指定してすべてのタスクを検索しようとしているようです。あなたは、単に

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}); 
}); 
[私は非同期呼び出しからの応答を返すにはどうしますか?](の
関連する問題