0

I am having some issues with block scoping in Node. I am attempting to build a object stuffed with some stats from the database. The issue I am running into is the object gets defined just fine inside of a mongoose db call, but is undefined outside of it.

I have also tried doing it as an array and doing stats.push(), and both ways with a setTimeout (set to 300ms). Any suggestions? I could do a method on the model I supposed, but I would rather learn about what i'm doing wrong here.

    app.get('/api/v1/authenticated/admin/stats/get', function(req, res) {
      let stats = {};
      User.find().count(function(err, count){
          stats.userCount = count;
      console.log('usrCnt inside of db ' + stats.userCount);  //defined.  Shows in the console after the console.log below.
      });
      console.log('UsrCount outside of db ' + stats.userCount);  //undefined
      res.send(stats);
    });
Taylor Ackley
  • 1,397
  • 1
  • 16
  • 31
  • Sooo...send the response in the callback to `count()` where you have the value. – slugonamission Jun 16 '16 at 20:26
  • 1
    Nothing to do with block scoping...everything to do with async. :) – JohnnyHK Jun 16 '16 at 20:27
  • @slugonamission, I could send the response, but what if I want to add additional counts from other models to the object and send the response all at once? – Taylor Ackley Jun 16 '16 at 20:28
  • 1
    Then use one of the functions from the `async` library, or only send the response when you have collected all of the results you need. The duplicate answer should have a few ways of doing this. – slugonamission Jun 16 '16 at 20:29

0 Answers0