0

Hi I get data from mongoDB and I try insert new data from other function. For some reason I get undefined. What I'm doing is wrong and how can I fix it?

router.post("/list", (req, res, next) => {
const params = req.body;
var results_data = [];
Countability.find()
    .populate("user")
    .populate("company")
    .populate("store")
    .exec(function (err, data) {
        _.forEach(data, function (value, key) {
            results_data[key] = {
                _id: value._id,
                count: GetCount(10)
            };
        });
        res.status(200).json({ status: 1, result: results_data });
    });

});


const GetCount = (id) => {
    DataRow.aggregate(
        [
        {
            "$group": {
                "_id": "$rowName",
                "count": { "$sum": 1 }
            }
        }

        ]).exec((err,res) => {

            var data = Promise.all([res]);
            data.then(function (res) {
                return res
            })

        })

}
Alex Malin
  • 63
  • 5
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jonas Wilms Aug 27 '17 at 08:48
  • Thanks i try this asynchronous response It's still return undefined – Alex Malin Aug 27 '17 at 11:41

1 Answers1

0

Though the forEach has not finished,server starts sending response. You need to make sure the results_data has got all data,then call res.status(200).json

Andrew Fan
  • 274
  • 2
  • 6