首页 > 解决方案 > Node MongoDB 循环遍历集合的第一条记录并将其推送到数组中

问题描述

我正在尝试按数字集合名称获取用户名列表。我已经创建了查询,似乎工作正常,但它没有推入数组,所以我可以返回整个数据作为对 api 的响应。

router.get('/chat-logs', async (req, res) => {
  const collections = Object.keys(db.db.collections);

  MongoClient.connect(url, { useUnifiedTopology: true }, function(err, dbm) {
    if (err) throw err;
    var dbo = dbm.db('dbname');
    let collections = dbo
      .listCollections()
      .toArray()
      .then(data => {
        let names = [];
        forEach(data, function(e) {
          let { name } = e;
          if (!isNaN(name)) {
            dbo.collection(name).findOne({}, function(err, result) {
              if (err) throw err;
                names[name] = `${result.first_name} ${result.last_name}`;
            });
          }
        });
        console.log(names)
        res.send(names);
      });
  });
});

如您所见,我正在获取所有集合名称,因为聊天日志与其相应的 ID 一起存储为集合,并且我正在循环它们并获取它们的最后一个字段。最后,我尝试将其推送到 names[] 数组中,以便我可以将它们全部收集并发送响应。问题是数组在查询范围之外仍然是空的。我有点卡在这一点上,我想知道是否有更简单的方法可以将所有集合的最后一个字段作为数组获取,如果没有,那么我该如何解决这个问题?

谢谢

标签: javascriptnode.jsmongodbexpress

解决方案


请参阅Node JS Promise.all 和 forEach

您也许可以执行以下操作:

router.get('/chat-logs', async (req, res) => {
  const collections = Object.keys(db.db.collections);

  MongoClient.connect(url, { useUnifiedTopology: true }, function(err, dbm) {
    if (err) throw err;
    var dbo = dbm.db('dbname');
    let collections = dbo
      .listCollections()
      .toArray()
      .then(data => {
        let names = [];
        i = 0;
        data.forEach(function(e) {
          let { name } = e;
          if (!isNaN(name)) {
            dbo.collection(name).findOne({}, function(err, result) {
              if (err) throw err;
              names.push(`${result.first_name} ${result.last_name}`);
              i=i+1;
              if(i>(names.length-1)){
                // all callbacks have finished. 
                console.log(names)
                res.send(names);
              }
            });
          }
        });

      });
  });
});

推荐阅读