Thursday, 11 May 2017

for each loop is not working in nodejs mongoose, shows error Can't set headers after they are sent

here i am running foreach loop, the error i am getting is Can't set headers after they are sent.

module.exports.landingPageTrove = function(req, res) {
              Trove.find({type: 'Trending', is_verified: true}, '_id title cover_image user_id').populate({path: 'user_id', select: 'profile_photo -_id'}).limit(4).sort({_id: -1}).exec(function(err, trove) {
                if (err) {
                  return res.send(err);
                } 
                else {
                  var link = {
                    "trending": {
                      "troves":""
                    }
                  };
                  trove.forEach(function(t){
                    Link.find({trove_id:t._id}, '_id title url').exec(function(err, result) {
                      console.log(result);
                      var temp = JSON.parse(JSON.stringify(t));
                      temp["links"] = result;
                      link['trending']["troves"] = temp;
                      res.status(200).send(link);
                    });
                  })
                }
              });
            };

the output which i am getting from this code is

enter image description here

But i want some thing like this

enter image description here



via Arvind

No comments:

Post a Comment