需要在forEach完成后发送响应

ale*_*hzr 3 mongoose mongodb node.js express

我正在使用NodeJS + Mongoose,我正在尝试填充一个对象数组,然后将其发送到客户端,但我不能这样做,响应始终为空,因为它是在每个结束之前发送的.

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

循环结束后有没有办法发送它?

Leo*_*tny 5

基本上,您可以使用异步控制流管理的任何解决方案,如异步或承诺(请参阅laggingreflex的答案以获取详细信息),但我建议您使用专门的Mongoose方法在一个MongoDB查询中填充整个数组.

最直接的解决方案是使用Query#populate方法获取已填充的文档:

Order.find({
  seller: req.session.passport.user
}).populate('customer').exec(function(err, orders) {
  //handle error
  res.json(orders);
});
Run Code Online (Sandbox Code Playgroud)

但是,如果由于某种原因,您无法使用此方法,您可以自己调用Model.populate方法来填充已经获取的文档数组:

Order.populate(orders, [{
  path: 'customer'
}], function(err, populated) {
  // ...
});
Run Code Online (Sandbox Code Playgroud)