Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

421
Views
MongoDB, forEach & Promise : How to know when a forEach loop is done?

In order to output a CSV file, I want to build an array of data from a MongoDB collection.

I use forEach into a promise and I want to resolve when all the records have been read.

However my code below does not work. The promise is never resolved. It seems there is a bug with the if/else condition. Is there another way to know when the forEach loop is done?

exports.eachRecord = function () {
  return new Promise(function (resolve, reject) {
    var data = []
    mongoClient.connect(process.env.MONGO, function (err, db) {
      // Handled connection error
      if (err) { return console.log(err) }
      db.collection('log').find().forEach(function (doc) {
        if (doc !== null) {
          console.log(doc.ug)
          data.push(doc.ug)
        } else {
          db.close()
          console.log('done!')
          resolve(data)
        }
      })
    })
  })
}

Any idea? Thank you very much.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

The mongodb, since v3.0, support the cursor.forEach(iterator, endCallback)

We must distinguish between:

  • array.forEach: it is sync and iterate an array of elements all loaded in memory after the toArray
  • mongoCursor.forEach: it is async and it is managed by the mongo driver. You are streaming the data, so you can put them to a file or to an http response.

So to archive your needsyou need only to add a callback:

    exports.eachRecord = function () {
      return new Promise(function (resolve, reject) {
        const data = []
        mongoClient.connect(process.env.MONGO, function (err, db) {
          if (err) { return reject(err) }

          db.collection('log').find().forEach(
            doc => { data.push(doc.ug) },
            err => {
              if (err) { return reject(err) }
              resolve(data)
            })
        })
      })
    }
over 4 years ago · Santiago Trujillo Report

0

forEach is synchronous.

The problem is with your mongodb call, which is not asynchronous. You can make it asynchronous by adding it a callback.

db.collection('log').find({}, (err, data) => {
  if (error) ...
  data.forEach((doc) => { ... });
  // Whatever you want to do after forEach.
});
over 4 years ago · Santiago Trujillo Report

0

You can use this code :

function getData() {
    return new Promise((resolve, reject) => {

        var data = db.collection('credit_history').find({
            'history.dt': '2019-04-25'
        }).toArray((err, res) => {
            if (err) reject(err);
            resolve(res);
        });
    }).catch((ex)=>{
        console.log(ex);
    });
}

   var array_data =[] ;
        var data = await getData().then((data)=>{
            data.forEach((el)=>{
                console.log(el.p);
                array_data.push(el.p) ;

            })
        });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!