Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Getting number of queries in a MongoDB collection in NodeJS

New to MongoDb, I am working on a small phonebook application where the user can add and remove phonebook entries using a name and phone number. I am able to successfully add and delete entries and have the database updated successfully, but not sure how to get the number of total entries/queries in a specific MongoDB collection.

MongoDB module:

const mongoose = require('mongoose')
const url = process.env.MONGODB_URI
console.log('connecting to', url)

mongoose.connect(url)
.then(result => {
    console.log('connected to MongoDB')
  })
.catch((error) => {
    console.log('error connecting to MongoDB:', error.message)
})

const personSchema = new mongoose.Schema({
    name: String,
    number: String,
}, { collection: 'phonebook' })

personSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Person', personSchema)

On my MongoDB cluster, the name of my DB is 'myFirstDatabase' and the collection name is 'phonebook'

Current DB looks like this: enter image description here

On index.js:

app.get('/info', (request, response) => {
    const date = new Date();
    const numPersons = Person.countDocuments()
    //Should be 2
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

countDocuments is asynchronous

Try with async await and add an empty {} inside countDocuments

app.get('/info', async(request, response) => {
    const date = new Date();
    const numPersons = await Person.countDocuments({})
    response.send(`Today is ${date} </br>There are ${numPersons} entries in the phonebook`)
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!