2014-02-11 3 views
0

이 경우 비동기 호출을 어떻게 피할 수 있습니까? res.render가 너무 빠르며 상태에서 개체가 누락 될 때마다 모든 것을 시도했습니다. playingCollection은 mongodb 컬렉션입니다. 다음은Mongodb 비동기 호출?

playingCollection.find({}).toArray(function(err, companies) { 

    if(err) { 
    res.render('error', {whatever}); 
    return; 
    } 

    var state = []; 
    var i; 
    for(i=0; i<companies.length; i++) { 
     state.push(companies[i].playername);   
    } 
    res.render('index', { title: 'Demo', error: req.query.error, players: state, head: 'Currently playing:'}); 

}); 

답변

1

여기) (찾기 위해 호출 한 후이 사용 toArray을 처리 할 수있는 하나의 방법입니다. 목록이 모두 소진 된 경우 each 호출이 null을 전달한다는 사실에만 의존합니다. 그것은 단지 playername을 반환, 위의에서

playingCollection.find({}, { playername: 1 }).each(....); 

: 당신은 당신이 컬렉션에서 하나 개의 필드에만 관심이 있었다 알았다면

var state = []; 
playingCollection.find({}).each(function(err, company) { 
    if (company !== null) { 
     state.push(company.playername); 
    } else { 
     res.render('index', { title: 'Demo', error: req.query.error, players: state, 
          head: 'Currently playing:'}); 
     return; 
    } 
});  

, 당신은 또한 옵션 projection 매개 변수를 사용하여 결과를 제한해야 각 문서의 필드는 _id입니다.

0

find에서 반환 된 Cursor 객체를 사용하여 간단한 방법입니다

var state = []; 
playingCollection.find({},function(err, companies) { 
    companies.each(function(err,company){ 
     if (company !== null) { 
      var obj = company.playername; 
      state.push(obj); 
     } 
     res.render('index', { title: 'Demo', error: req.query.error, players: state, head: 'Currently playing:'}); 
     state = []; 
     return; 
    }); 
});