-1

I am trying to fetch a list of user names by numeric collection names. I have created the query and seems to be working fine but its not pushing into the array so i can return the entire data as response for the 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);
      });
  });
});

as you can see I am getting all the collection names because the chat logs are stored with their corresponding ids as a collection, and I am looping through them and fetching their last fields. At the end I am trying to push it inside names[] array so I can collect them all and send the response. The problem is that the array remains empty outside the query scope. I am kind of stuck at this point, I was wondering if there's any much more easier way to get all collections with their last fields as an array, and if not then how can I fix this?

thanks

Areg
  • 1,414
  • 1
  • 19
  • 39

1 Answers1

1

See Node JS Promise.all and forEach

You may be able to do something like this:

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);
              }
            });
          }
        });

      });
  });
});
Cody G
  • 8,368
  • 2
  • 35
  • 50