我试图从MongoDB中获取多个文档并将所有数据发送到一个数组中,但是在理解如何使用事件驱动的Node.js来完成此操作时遇到了严重的麻烦。

问题是在执行dataArray.push(tempObject)时,仍然没有执行tempObject["data"] = tempDataArray

我的代码如下所示:

app.post('/api/charts', function(req, res) {
  var names = req.body.names;
  var categories = req.body.categories;

  var dataArray = [];

  for (i = 0; i < names.length; i++) {
    var tempObject = {};
    tempObject["name"] = names[i];
    Company.find({ name : names[i] }, function(err, result) {
      if (err) {
        throw err;
      }

      var tempDataArray = [];

      for (k = 0; k < categories.length; k++) {
        var tempDataObject = {};
        tempDataObject["name"] = categories[k];
        tempDataObject["numbers"] = result[0]["data"][categories[k]]["numbers"];
        tempDataObject["dates"] = result[0]["data"][categories[k]]["dates"];

        tempDataArray.push(tempDataObject);

      }
      tempObject["data"] = tempDataArray;
    });

    dataArray.push(tempObject);
  }

  res.send(dataArray);
});

任何关于如何适当地获得期望结果的建议将不胜感激。

最佳答案

使用这个图书馆

https://github.com/caolan/async

使用此代码,您的代码将如下所示:
var async = require("async");
app.post('/api/charts', function(req, res) {
    var names = req.body.names;
    var categories = req.body.categories;

    var dataArray = [];

    async.forEach(names, function(name, callback){

        var tempObject = {};
        tempObject["name"] = name;
        Company.find({ name : name }, function(err, result) {
            if (err) {
                callback(err);
            } else {
                var tempDataArray = [];

                for (k = 0; k < categories.length; k++) {
                    var tempDataObject = {};
                    tempDataObject["name"] = categories[k];
                    tempDataObject["numbers"] = result[0]["data"][categories[k]]["numbers"];
                    tempDataObject["dates"] = result[0]["data"][categories[k]]["dates"];

                    tempDataArray.push(tempDataObject);

                }
                tempObject["data"] = tempDataArray;
                dataArray.push(tempObject);
                callback();
            }
        });
    }, function(err){
        if(err){
            res.send(err);
        } else {
            res.send(dataArray);
        }
    });

});

10-05 19:24