node js nested loop results finally push to single array

穿精又带淫゛_ 提交于 2019-12-11 16:17:20

问题


i will get the Array of Answers

but how to get the Answered users info;

the flow is Get List of Posts, Post User Info, Post User Followers Count, Post Likes Count, Login User Liked The Post True or False, Answers, Answered User Info and Answered User Followers Count

exports.GetPostList = function(req, res) {
    var SkipCoun = 0;
    SkipCoun = parseInt(req.params.Limit) * 10;
     QuestionsPostModel.QuestionsPostType.find({}, {} , {sort:{createdAt : -1}, skip: SkipCoun, limit: 10  }, function(err, result) {
        if(err) {
            res.status(500).send({status:"False", message: "Some error occurred while Find Following Users ."});
        } else {
                const GetUserData = (result) =>
                    Promise.all(
                        result.map(info => getPostInfo(info))
                    ).then(
                        results => {
                            let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray ] = 
                            results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix ], [one, two, three, four, five, six]) => 
                            [allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [ [], [], [], [], [], [] ]);
                            res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount:AnswersCount, AswersArray:AswersArray })
                        }
                    ).catch(err => res.send({ status: "Fale",Error: err}) );


                const getPostInfo = info =>
                    Promise.all([
                        UserModel.UserType.findOne({'_id': info.UserId }, usersProjection).exec(),
                        FollowModel.FollowUserType.count({'UserId': info.UserId}).exec(),
                        RatingModel.QuestionsRating.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
                        RatingModel.QuestionsRating.count({'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates':'Active'}).exec(),
                        AnswerModel.QuestionsAnwer.count({'PostId': info._id , 'ActiveStates':'Active' }).exec(),
                        AnswerModel.QuestionsAnwer.find({ 'PostId':info._id }, 'AnswerText UserId Date' ).exec()
                    ]);

            GetUserData(result);

        }
     });
    };

How to Get The Result


回答1:


as you formed the array, and you are passing it inside Promise.all() . and you just need the data.

Promise.all() docs.

see Below Code (we can just do as promise .then() and .catch()):

exports.GetPostList = function (req, res) {
    var SkipCoun = 0;
    SkipCoun = parseInt(req.params.Limit) * 10;
    QuestionsPostModel.QuestionsPostType.find({}, {}, { sort: { createdAt: -1 }, skip: SkipCoun, limit: 10 }, function (err, result) {
        if (err) {
            res.status(500).send({ status: "False", message: "Some error occurred while Find Following Users ." });
        } else {
            const GetUserData = (result) =>
                Promise.all(
                    result.map(info => getPostInfo(info))
                ).then(
                    results => {
                        let [UserInfo, UserFollowers, PostRatingCount, UserRatedCount, AnswersCount, AswersArray] =
                            results.reduce(([allOne, allTwo, allThree, allFour, allFive, allSix], [one, two, three, four, five, six]) =>
                                [allOne.concat([one]), allTwo.concat([two]), allThree.concat([three]), allFour.concat([four]), allFive.concat([five]), allSix.concat([six])], [[], [], [], [], [], []]);
                        res.send({ status: "True", UserInfo: UserInfo, UserFollowers: UserFollowers, PostRatingCount: PostRatingCount, UserRatedCount: UserRatedCount, AnswersCount: AnswersCount, AswersArray: AswersArray })
                    }
                    ).catch(err => res.send({ status: "Fale", Error: err }));


            const getPostInfo = info =>
                Promise.all([
                    UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
                    FollowModel.FollowUserType.count({ 'UserId': info.UserId }).exec(),
                    RatingModel.QuestionsRating.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                    RatingModel.QuestionsRating.count({ 'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates': 'Active' }).exec(),
                    AnswerModel.QuestionsAnwer.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                    AnswerModel.QuestionsAnwer.find({ 'PostId': info._id }, 'AnswerText UserId Date').exec()
                ]).then(data => {
                    let userData = data[0];
                    let followCount = data[1];
                    let ratingCount = data[2];
                    let ratingCountBy_postId = data[3];
                    let answerCount = data[4];
                    let answers = data[5];
                    // now you may need to construct some object or something and pass data as you required.
                    let result = {
                        user: userData,
                        follow_count: followCount,
                        rating_count: ratingCount,
                        rating_countBy_postId: ratingCountBy_postId,
                        answer_count: answerCount,
                        answers: answers
                    };

                }).catch(error => {
                    console.log(error)
                })


                    GetUserData(result);

        }
    });
};



回答2:


exports.GetPostList = function (req, res) {
var SkipCoun = 0;
SkipCoun = parseInt(req.params.Limit) * 10;
QuestionsPostModel.QuestionsPostType.find({}, {}, { sort: { createdAt: -1 }, skip: SkipCoun, limit: 10 }, function (err, result) {
    if (err) {
        res.status(500).send({ status: "False", message: "Some error occurred while Find Following Users ." });
    } else {
        const GetUserData = (result) =>
            Promise.all(
                result.map(info => getPostInfo(info))
            ).then( result =>{ console.log(result);  res.send({ status: "True", data: result }) }
            ).catch(err => res.send({ status: "False", Error: err }));


        const getPostInfo = info =>
            Promise.all([
                UserModel.UserType.findOne({ '_id': info.UserId }, usersProjection).exec(),
                FollowModel.FollowUserType.count({ 'UserId': info.UserId }).exec(),
                RatingModel.QuestionsRating.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                RatingModel.QuestionsRating.count({ 'UserId': req.params.UserId, 'PostId': info._id, 'PostUserId': info.UserId, 'ActiveStates': 'Active' }).exec(),
                AnswerModel.QuestionsAnwer.count({ 'PostId': info._id, 'ActiveStates': 'Active' }).exec(),
                AnswerModel.QuestionsAnwer.find({ 'PostId': info._id }, 'AnswerText UserId Date').exec()
            ]).then(data => {
                let UserData = data[0];
                let followCount = data[1];
                let ratingCount = data[2];
                let UserRating = data[3];
                let AnswerCount = data[4];
                let Answerdata = data[5];


                var AnswersArray= new Array();

               return GetAnsUserData();
                async function GetAnsUserData(){
                    for (let ansInfo of Answerdata) {
                        await getAnswerInfo(ansInfo);
                     }

                     let result = {
                        _id: info._id,
                        UserId: UserData._id,
                        UserName: UserData.UserName,
                        UserCategoryId: UserData.UserCategoryId,
                        UserCategoryName: UserData.UserCategoryName,
                        UserImage: UserData.UserImage,
                        UserCompany: UserData.UserCompany,
                        UserProfession: UserData.UserProfession,
                        Followers:followCount,
                        PostTopicId: info.PostTopicId,
                        PostTopicName: info.PostTopicName,
                        PostDate: info.PostDate,
                        PostText: info.PostText ,
                        PostLink: info.PostLink,
                        PostImage: info.PostImage,
                        PostVideo: info.PostVideo,
                        RatingCount: ratingCount,
                        UserRating: UserRating,
                        AnswersCount: AnswerCount,
                        Answers: AnswersArray,

                    };
                    return result;
                  }

                  function getAnswerInfo(ansInfo){
                    return new Promise(( resolve, reject )=>{
                        UserModel.UserType.findOne({'_id': ansInfo.UserId }, usersProjection, function(err, AnsUserData) {
                            if(err) {
                                res.send({status:"Fale", Error:err });
                                reject(err);
                            } else {
                                FollowModel.FollowUserType.count({'UserId': AnsUserData._id}, function(newerr, count) {
                                    if(newerr){
                                        res.send({status:"Fale", Error:newerr });
                                        reject(newerr);
                                    }else{
                                        var newArray = [];
                                        newArray.push( {
                                                        _id: ansInfo._id,
                                                        UserId: AnsUserData._id,
                                                        UserName: AnsUserData.UserName,
                                                        UserCategoryId: AnsUserData.UserCategoryId,
                                                        UserCategoryName: AnsUserData.UserCategoryName,
                                                        UserImage: AnsUserData.UserImage,
                                                        UserCompany: AnsUserData.UserCompany,
                                                        UserProfession: AnsUserData.UserProfession,
                                                        Followers: count,
                                                        Date: ansInfo.Date,
                                                        PostId: ansInfo.PostId,
                                                        PostUserId: ansInfo.PostUserId ,
                                                        AnswerText: ansInfo.AnswerText
                                                    }
                                        );
                                        AnswersArray.push(newArray[0]);
                                        resolve(newArray[0]);
                                    }
                                });
                            }
                        });
                    });
                }


            }).catch(error => {
                console.log(error)
            })

         GetUserData(result);

    }
 });
};

Finally I get The Answer Thanks To ALL



来源:https://stackoverflow.com/questions/48597193/node-js-nested-loop-results-finally-push-to-single-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!