如何计算mongodb集合中特定字段的实例

时间:2019-02-10 06:35:48

标签: node.js mongodb

这是我的mongodb中的付款集合。

{
studentIDnumber: "111"
datepicker: "02/06/2019"
transactType: "Graduation expenses"
timepicker:"11:00am - 12:00pm"
amount:"123"
}

{
studentIDnumber: "111"
datepicker: "02/03/2019"
transactType: "Diploma"
timepicker:"11:00am - 12:00pm"
amount:"123"
}

{
studentIDnumber: "111"
datepicker: "02/03/2019"
transactType: "Tuition fee"
timepicker:"11:00am - 12:00pm"
amount:"123"
}

我试图计算集合中有11:00-12:00 pm,但是它给了我UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'count' of undefined,下面是我的nodejs代码。正确的方法是什么?有什么想法吗?

const mongoose = require('mongoose')
const url = require('../config/keys').MongoURI

router.get('/dashboard', ensureAuthenticated, (req, res) =>{
  res.render('dashboard', {
    firstname: req.user.firstname,
    lastname : req.user.lastname
  }),

  mongoose.connect(url, {useNewUrlParser: true}, function(err, db){
    if (err) throw err
    db.payments.count({timepicker: "11:00am - 12:00pm"})

  })

});

1 个答案:

答案 0 :(得分:1)

使用此查询:

db.payments.find({timepicker: "11:00am - 12:00pm"}).count(function(err, count) 
    {
        if (err) throw err;
        console.log(count);

    });

如果您使用猫鼬,则

 PaymentModel.count({timepicker: "11:00am - 12:00pm"}, function(err, c) {
       console.log('Count is ' + c);
  });