node.js - Need to send response after forEach is done -
i'm working nodejs + mongoose , i'm trying populate array of objects , send client, can't it, response empty because sent before foreach ends.
router.get('/', isauthenticated, function(req, res) { order.find({ seller: req.session.passport.user }, function(err, orders) { //handle error var response = []; orders.foreach(function(doc) { doc.populate('customer', function(err, order) { //handle error response.push(order); }); }); res.json(response); }); });
is there way send after loop has finished?
basically, use solution async control flow management async or promises (see laggingreflex's answer details), recommend use specialized mongoose methods populate whole array in 1 mongodb query.
the straightforward solution use query#populate
method populated documents:
order.find({ seller: req.session.passport.user }).populate('customer').exec(function(err, orders) { //handle error res.json(orders); });
but if, reason, can't use method, call model.populate
method populate array of fetched docs:
order.populate(orders, [{ path: 'customer' }], function(err, populated) { // ... });
Comments
Post a Comment