Reputation: 39
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
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
Reputation: 39
Fixed it with
return Promise.all([
db.collection(col["name"]).countDocuments(),
Promise.resolve(col["name"])
]);
Upvotes: 0