1

I have a bunch of profiles in my ReadyForReview collection. Each profile contains a 'user_id_to_review' field. I want to use user_id_to_review to append the user's information from the Users collection to each profile.

// 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
    }

})

However, i in the User.find function is wrong due to async. How can I achieve an array of profiles and user information?

1 Answer 1

1

Use the async library to do your loops. 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
        });
});
Sign up to request clarification or add additional context in comments.

2 Comments

I think you're correct here but that reference to profilesReadyForReview[i] should probably be just profile
Works! Thanks to you both! May the code Gods shine brightly on your day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.