How to get count of documents in a query result in mongoose?
Mar 15, 2023
To get count of query result:
model.find(queryObj).countDocuments();
To get count of docs in entire collection:
model.estimatedDocumentCount();
try {
await mongoose.connect(this.mongoDBUrl);
let collectionName = config.mongoCollectionMap[resource];
let model = mongoose.model(collectionName);
if (!queryObj || Object.entries(queryObj).length === 0) {
return await model.estimatedDocumentCount();
} else {
return await model.find(queryObj).countDocuments();
}
} catch (err) {
console.log(err);
throw err;
}