Home > Net >  how i get total count of data from collection
how i get total count of data from collection

Time:09-08

getTotalCount = (req, res) => {
        let params = req.body
        console.log('params#####', params.query)
        return new Promise((resolve, reject) => {
            try {
                MongoClient.connect(mongoDbUrl, (err, db) => {
                    if (err) throw err
                    let dbo = db.db(dbName)

                    dbo.collection('error_logs').count((err, res) =>
                        err ? reject(err) : res.find().then((x) => resolve(x))
                    )
                })
            } catch (e) {
                console.log('error##### get log', err)
                res.send({ status: 'fail', data: e })
            }
        })
    }

I get error:- res.find is not a function.

How i get total count of data of collection.

CodePudding user response:

You cannot call find function after count method is called. For more information kindly refer to the official documentation of mongoDB And just for refernce I am also sharing the code

db.orders.count()

or

db.orders.find().count()

and you can directly assign its value to a variable or constant like

const orderCount=await db.orders.find().count()

CodePudding user response:

getTotalCount = (req, res) => {
    let params = req.body
    console.log('params#####', params.query)
    return new Promise((resolve, reject) => {
        try {
            MongoClient.connect(mongoDbUrl, (err, db) => {
                if (err) throw err
                let dbo = db.db(dbName)

                dbo.collection('error_logs').count(
                    params.query ? params.query : {},
                    (err, result) => {
                        db.close()
                        if (err) {
                            res.send({ status: 'fail', data: err })
                        } else {
                            res.send({ status: 'success', data: result })
                        }
                    }
                )
            })
        } catch (e) {
            console.log('error##### get log', err)
            res.send({ status: 'fail', data: e })
        }
    })
}
  • Related