繁体   English   中英

猫鼬+ Node.js:异步问题

[英]Mongoose + Node.js : Async issue

我的ReadyForReview集合中有很多配置文件。 每个配置文件都包含一个“ user_id_to_review”字段。 我想使用user_id_to_review将来自Users集合的用户信息附加到每个配置文件。

// 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错误。 如何获得一系列的个人资料和用户信息?

使用异步库执行循环。 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
        });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM