Mongoose + Node.js:asynchronous问题

我在ReadyForReview集合中有一堆configuration文件。 每个configuration文件都包含一个“user_id_to_review”字段。 我想使用user_id_to_review将Users集合中的用户信息附加到每个configuration文件。

// 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函数中是由于asynchronous错误的。 我如何获得一组configuration文件和用户信息?

使用asynchronous库来做你的循环。 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 }); });