【问题标题】:Getting number of queries in a MongoDB collection in NodeJS在 NodeJS 中获取 MongoDB 集合中的查询数
【发布时间】:2022-02-11 13:06:11
【问题描述】:

MongoDb 新手,我正在开发一个小型电话簿应用程序,用户可以在其中使用姓名和电话号码添加和删除电话簿条目。我能够成功添加和删除条目并成功更新数据库,但不确定如何获取特定 MongoDB 集合中的总条目/查询数。

MongoDB 模块:

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)

在我的 MongoDB 集群上,我的数据库名称是“myFirstDatabase”,集合名称是“电话簿”

当前数据库如下所示:

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

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    countDocuments 是异步的

    尝试使用 async await 并在 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`)
    })
    

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2013-08-15
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多