the_dude
the_dude

Reputation: 39

nodejs return array of objects from mongodb

I want to return an array of objects that contains collection name and its documents count for each object, e.g. [ { col:col1, count:1 } , { col:col2, count:2} ]

Currently I only return an array of document count for each collection, by resolving the query as a promise.

My main issue is returning an object from the .map function because it must return promises instead.

db.listCollections()
  .toArray()
  .then(collections => {
    let promises = collections.map(col => {

      // Cannot return {col,count} here :/
      return db.collection(col["name"]).countDocuments();
    });
    return Promise.all(promises);
  })
  .then(res => console.log(res));

Upvotes: 1

Views: 1150

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51766

Alternatively, passing an async function to collections.map(), you could return { col, count }:

db.listCollections()
  .toArray()
  .then(collections => {
    const promises = collections.map(async col => {
      return {
        col: col.name,
        count: await db.collection(col.name).countDocuments()
      };
    });
    return Promise.all(promises);
  })
  .then(res => { console.log(res); });

Upvotes: 1

the_dude
the_dude

Reputation: 39

Fixed it with

return Promise.all([
    db.collection(col["name"]).countDocuments(),
    Promise.resolve(col["name"])
]);

Upvotes: 0

Related Questions