How can use the .count() method in mongoose to count multiple collections

Issue

I have a operation that counts all of the registered users which there is a collection named registered-users in my MongoDB.
Here is how I accomplished that:

    const User = require("../models/User")
    const Topic = require("../models/Topic")

    router.get('/', async (req, res) => {
        await User.count((err, registeredUsers) => {
            if (err){
                console.log(err) 
            } else {
                    res.render("register", {registeredUsers})// using EJS for my template engine
            }
        })
    
    })

so this let’s me count the total users registered but I have another collection in the db named topics that I would like to get a total count of as well. how can I do that without having to res.render again (I’m not even sure if that works or not) and pass in another object? Is this possible to count the users and the topics (which is a different collection and model)?

The goal is that in the ejs it has something that says :

Total Users signed up: registeredUsers

Total Topics created: totalTopics

Solution

Model.count()

Counts number of documents that match filter in a database collection.

This method is deprecated. If you want to count the number of documents in a collection, e.g. count({}), use the estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.

source: https://mongoosejs.com/docs/api.html#model_Model-count

Also, since you are using async function, we can use Promise.all() to run queries in parallel.

const User = require("../models/User")
const Topic = require("../models/Topic")

router.get('/', async (req, res) => {
  const [userCount, topicCount] = await Promise.all([
   User.countDocuments({}),
   Topic.countDocuments({})
  ])

  // using EJS for my template engine
  res.render("register", {
    registeredUsers: userCount,
    totalTopics: topicCount
  })

})

Answered By – Sridhar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published