2014-06-11 25 views
0

我試圖從此函數返回數據。 Console.log(文檔)在控制檯中成功顯示數據。但是這隻在功能的主體中起作用。我無法將這些數據返回給模板。我該怎麼辦?我應該使用node.js的一些異步包,還是可以像這樣以某種方式完成?node.js從循環中查找集合返回數據

謝謝。

var projects = req.user.projects; 
var docs = []; 

db.collection('documents', function(err, collection) { 
    for (i = 0; i < projects.length; i++) { 
     collection.find({'_projectDn': projects[i].dn},function(err, cursor) { 
      cursor.each(function(err, documents) { 
       if(documents != null){ 
        console.log(documents); 
        //or docs += documents; 
       } 
      }); 
     }); 
    } 
}); 

console.log(documents); // undefined 

res.render('projects.handlebars', { 
    user : req.user, 
    documents: docs 
}); 
+2

你可能想看看https://github.com/maxogden/art-of-node#callbacks。 –

回答

4

這些db函數是異步的,這意味着當你嘗試記錄它時,函數還沒有完成。您可以使用callback記錄它,例如:

function getDocuments(callback) { 
     db.collection('documents', function(err, collection) { 
      for (i = 0; i < projects.length; i++) { 
       collection.find({ 
        '_projectDn': projects[i].dn 
       }, function(err, cursor) { 
        cursor.each(function(err, documents) { 
         if (documents !== null) { 
          console.log(documents); 
          callback(documents);// run the function given in the callback argument 
         } 
        }); 
       }); 
      } 
     }); 
    } 
//use the function passing another function as argument 
getDocuments(function(documents) { 
    console.log('Documents: ' + documents); 
});