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