2014-06-11 3 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); 
}); 
관련 문제