How to retrieve key value from mongdb find()

Viewed 22

Below is my code, clientNames is an array of strings.

function GetCollectionAllowance(clientNames) {
    // Retrieves client names from DB and adds to Array
    MongoClient.connect('x', function (err, client) {
      if (err) throw err

        // DB Name
        var db = client.db('client-time')


        clientNames.forEach((element) => {

          db.collection(element).find( {}, {allowance:1} )
          .then(function(allowance) {
            
            console.log(allowance); // Use this to debug
          })
      

        })
    
    })

}

This is the error I'm receiving -

/home/nolwag/Node/toggl/routes/index.js:229
          .then(function(allowance) {
           ^

TypeError: db.collection(...).find(...).then is not a function
    at /home/nolwag/Node/toggl/routes/index.js:229:16
    at Array.forEach (<anonymous>)
    at /home/nolwag/Node/toggl/routes/index.js:225:25
    at /home/nolwag/Node/toggl/node_modules/mongodb/lib/utils.js:532:9
    at /home/nolwag/Node/toggl/node_modules/mongodb/lib/mongo_client.js:130:17
    at connectCallback (/home/nolwag/Node/toggl/node_modules/mongodb/lib/operations/connect.js:38:9)
    at /home/nolwag/Node/toggl/node_modules/mongodb/lib/operations/connect.js:89:9
    at /home/nolwag/Node/toggl/node_modules/mongodb/lib/sdam/topology.js:231:25
    at /home/nolwag/Node/toggl/node_modules/mongodb/lib/cmap/connection_pool.js:272:25
    at handleOperationResult (/home/nolwag/Node/toggl/node_modules/mongodb/lib/sdam/server.js:363:9)

https://docs.mongodb.com/manual/crud/ - I'm copying the documentation and it seems that it's just this find that's not working. If I append .count() to the end of it, it returns normally.

1 Answers

Adding async to the beginning of my function resolved this error!

  async function GetCollectionAllowance(clientNames) {
Related