skip to Main Content
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.

2

Answers


  1. Chosen as BEST ANSWER
    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 })
            }
        })
    }
    

  2. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search