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

Time:09-05

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

CodePudding user response:

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

})
  • Related