0

I wrote this function to get a document from the end of the collection in MongoDB. When I try calling this function in index.js, it returns undefined.

index.js:

app.get('/', authenticate, function(req, res){

  // console.log("DATA: " + getWorldStatsData());
    everything = {
      worldstats: getWorldStatsData(),

    }

    res.render('index', {
      data: everything

  })
})

and my function:

function getWorldStatsData(){


    db.collection('worldstats').find({}).sort({"statistic_taken_at":-1}).limit(1).toArray((err, stats)=>{

      return stats
    })

  // return stats
}
F. Krovinsky
  • 9
  • 1
  • 4
  • You managed to use callbacks correctly in only one of those two cases. See https://stackoverflow.com/q/14220321/3001761 – jonrsharpe Apr 24 '20 at 18:36

1 Answers1

0

As jonrsharpe suggested, this is happening because the code that fetches the data is asyncroous. That means you need to implement some kind of callback to notify the surrounding function when the operation is complete A simple example:

index

app.get('/', authenticate, async function(req, res){

  // console.log("DATA: " + getWorldStatsData());
    everything = {
      worldstats: await getWorldStatsData(),

    }

    res.render('index', {
      data: everything

  })
})

your funciton:

function getWorldStatsData(){
      return db.collection('worldstats').find({}).sort({"statistic_taken_at":-1}).limit(1).toArray((err, stats)=>{

          return stats
        })

      // return stats
    }

Please take a look at the link provided by jonrsharpe for a better understanding

Kisinga
  • 1,640
  • 18
  • 27