Forcing array of promises to complete before returning
forEach vs map

When using map function, we're supposed to return something back from the function parameter. In the code above you do map and populate the promises collection by pushing to it. If you want to have the external collection as it is now, a forEach should be more readable than a map.

With map, the function may look like this. Also, notice that this allows joining the declaration and the assignment of promises array within the body of then(...):



let records = {}
nosqldb.get().listCollections().toArray()
  .then(collectionList =&gt; {
    const promises = collectionList.map(collection =&gt;
      nosqldb.get().collection(collection.name).count().then(count =&gt; { records[collection.name] = count; })
    );
    return Promise.all(promises);
  })
  .then(() =&gt; res.status(200).json(records))
  .catch((err) =&gt; res.status(500).send(err));


Side note

You may want to limit the number of collections in which you do .count(). If you have dozens or hundreds or even more collections, you this function may attempt to open as many connections (IDK the details). Also, the function execution time will be really long.

A typical solution in limiting is pagination and/or filtration of the things being counted.