1

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

2 Answers 2

1

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); });
Sign up to request clarification or add additional context in comments.

Comments

0

Fixed it with

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

1 Comment

The Promise.resolve() around col["name"] is not necessary, and you also don't need a computed property to do that, so the simplified answer would be return Promise.all([db.collection(col.name).countDocuments(), col.name])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.