Search code examples
ajaxnode.jsmongodbmonk

Getting the total number of records of a collection in mongodb using node js + monk + ajax


Total noob here, i only know how to do CRUD in Mongodb using node js+monk+ajax but I don't have any idea on how to get the total number of records in my collection.

This is what i have tried so far and it is returning undefined value:

router.get('/getTotalrecord'', function (req, res) { 
    var db = req.db; 
    var collection = db.get('department'); 
    res.send(collection.count); 
});

Solution

  • you should use this function

    exports.getCount = (req, res, next) => {
      Users.find({}, { __v: 0 })
        .then(users =>
          res.status(200).json({
            status: true,
            error_num: '',
            result: users.length,
            error: ''
          })
        )
        .catch(err => {
          next(err);
        });
    };