2014-12-20 4 views
1

내 ReadyForReview 컬렉션에 여러 개의 프로필이 있습니다. 각 프로필에는 'user_id_to_review'입력란이 있습니다. user_id_to_review를 사용하여 Users 컬렉션의 사용자 정보를 각 프로필에 추가하고 싶습니다. User.find 함수 그러나몽구스 + Node.js : 비동기 문제

// looking for all ReadyForReview profiles 
ReadyForReview.find() 
.exec(function(err, profilesReadyForReview) { 
    var profilesReadyForReviewArray = [] //array that will be populated with profiles and user info 

    // for each profile, figure out what the info for the user is from user table 
    for (var i = 0; i < profilesReadyForReview.length; i++) { 
     var thisUserProfile = profilesReadyForReview[i].user_id_to_review.toObjectId() // create objectID version of user_id_to_review 
     User.find({ 
       '_id': thisUserProfile 
      }) 
      .exec(function(err, user_whose_profile_it_is) { 
       profilesReadyForReviewArray.push({ 
        profile: profilesReadyForReview[i], 
        user: user_whose_profile_it_is 
       }) 
      }) 
     console.dir(profilesReadyforReviewArray) // should be an array of profiles and user info 
    } 

}) 

, 비동기로 인한 문제이다. 프로필 및 사용자 정보 배열을 어떻게 얻을 수 있습니까?

답변

1

루프를 수행하려면 비동기 라이브러리를 사용하십시오. https://github.com/caolan/async

// looking for all ReadyForReview profiles 
ReadyForReview.find() 
.exec(function(err, profilesReadyForReview) { 
    var profilesReadyForReviewArray = [] //array that will be populated with profiles and user info 

    // for each profile, figure out what the info for the user is from user table 
    async.each(profilesprofilesReadyForReview, function(profile, done) { 
     var profileId = profile.user_id_to_review.toObjectId() // create objectID version of user_id_to_review 
     User.find({ 
       '_id': profileId 
      }) 
      .exec(function(err, user_whose_profile_it_is) { 
       profilesReadyForReviewArray.push({ 
        profile: profile, 
        user: user_whose_profile_it_is 
       }) 
       done(); 
      }); 
     }, function(){ 
      console.dir(profilesReadyforReviewArray) // should be an array of profiles and user info 
     }); 
}); 
+1

난 그냥' – Pointy

+0

작품을 profile' 당신이 여기 맞아요하지만 profilesReadyForReview [i]는''에 해당 참조가 아마해야한다고 생각! 둘 다 감사합니다! 코드 신이 하루 종일 밝게 빛나기를 바랍니다. – Dev

+0

@Pointy 고정, 감사합니다. –