Tushar
Tushar

Reputation: 126

how can i count all users and posts in mongoDB

I want to count the user, posts, and comments of the website, and send data to the dashboard, which shows counts of all users and posts. I am unable to solve this. here is my code

     app.get('/', async (req,res)=>{
       const query = User.find()
       const posts = Post.find()
      const user = await query.countDocuments((err,count)=>{
           if(err){
               console.log(err)
           }else{
               return count;
           }
       })
   const post = await posts.countDocuments((err , posts)=>{
    if(err){
        console.log(err)
    }else{
        return posts;
    }
   })
console.log(post)
   res.render('dashboard',{userCount: user , posts:post})

})

Upvotes: 1

Views: 388

Answers (1)

Mohamed Ismail
Mohamed Ismail

Reputation: 367

You can find the number of documents using aggregation:

const postCount = await posts.aggregate([{$group: {
  _id : null,
  count : { $sum : 1}
}}, {$project: {
  _id : 0
}}]);

You will get output like: count : 11

Explanation

$group stage will select distinct records. When set to null it selects all records in the collection.

$project stage will select which fields we needed to output ( Since we needed only count we can eliminate others )

Upvotes: 2

Related Questions