我的ReadyForReview系列中有很多配置文件。每个配置文件都包含一个&user; id_to_review'领域。我想使用user_id_to_review将用户集合中的用户信息附加到每个配置文件。
// 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
}
})
但是,由于异步,User.find函数中的 i 是错误的。如何获得一系列配置文件和用户信息?
答案 0 :(得分: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
});
});