2012-01-17 4 views
2

node.js & mongoose을 사용하여 MongoDB 컬렉션의 여러 문서를 배열에 넣으려고합니다. _.each -loop의 userDoc 로깅은 정상적으로 작동하지만 어레이에 추가하지는 않습니다.MongoDB로 MongoDB에서 데이터 가져 오기

내가 뭘 잘못하고 있니?
내 생각 엔 노드의 비동기 디자인과 관련하여 뭔가 잘못 이해하고 있지만, 내가 무엇을 바꿔야하는지 잘 모른다는 것입니다.

의견 코드 :

returnObject.list = []; 

Users.find({}, function (err, user){ 

    _.each(user, function(userDoc){    
     console.log(userDoc); // Works 
     returnObject.list.push(userDoc); // No errors, but no users appended 
    }); 

}); 


console.log(returnObject); // No users here! 

res.send(JSON.stringify(returnObject)); // Aint no users here either! 

답변

5

아이, 당신이 동기 스타일로 뭔가를 할 수있는 좋은 하나의 시도하고있다 :

Users.find({}, function (err, user){ 
    // here you are iterating through the users 
    // but you don't know when it will finish 
}); 

// no users here because this gets called before any user 
// is inserted into the array 
console.log(returnObject); 

는 대신에이 같은 일을 수행해야합니다

var callback = function (obj) { 
    console.log(obj); 
} 

Users.find({}, function (err, user){ 
    var counter = user.length; 

    _.each(user, function(userDoc) { 
    if (counter) { 
     returnObject.list.push(userDoc);   
     // we decrease the counter until 
     // it's 0 and the callback gets called 
     counter--; 
    } else { 
     // since the counter is 0 
     // this means all the users have been inserted into the array 
     callback(returnObject); 
    } 
    }); 

}); 
+0

답안과 상세한 예제에 감사드립니다! 매우 높이 평가 됨 – Industrial

+0

항상 도와 줘서 기쁩니다! – alessioalex

0

당신이 각 루프 전에 무엇을 볼 수있는 util.inspect(user)을한다.

+0

네 - 사용자 데이터가 거기서 그것을 실행하면, 그래서 나는 빈 콜렉션에서 이것을 실행하지 않을 것입니다. – Industrial

관련 문제