Home > Software engineering >  Getting number of queries in a MongoDB collection in NodeJS
Getting number of queries in a MongoDB collection in NodeJS

Time:02-11

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

CodePudding user response:

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`)
})
  • Related