1

I'm new to Node.js, and am trying to make a simple web app using express. The general idea is that the app will pull documents from my Mongo DB using the native Node driver, create an array for the results, and then their properties will be exposed in an express HTML response.

The issue I'm having is that I cannot create a variable outside of the initial DB call, and any variable I create, no matter how I create it, ends up being undefined when included in my express response.

I've unsuccessfully iterated this so many times I'm not sure what to try next. I feel like I have read every stack question on the subject. I've read up on async programming and think I understand the fundamentals. I've tried different callbacks and tried creating a promise without any luck.

I'm about to resort to sorcery.

Here's a sample DB response:

[ { _id: 5a1a2aa6dc888a00145b7fe3,
target: 'latest1' },
{ _id: 5a1a2ab3dc888a00145b7fe4,
target: 'latest2' } ]

Here's the relevant code:

var finalResult;

function getTargets(err, db) {
  if (err) throw err;
  db.collection('targets').find({}).toArray(saveTargets)};

function saveTargets(err, result) {
    if (err) throw err;
    console.log(result); // this works
    finalResult = result;
    };

app.get('/upcomingtargets', (req, res) => {

    MongoClient.connect(dbURL, getTargets);
    res.writeHead(200, {'Content-type': 'text/html'});
    res.end(finalResult[0].name); // just to verify that something is there

});

The result of res.end(finalResult[0].name); is inevitably undefined

My ideal response would be something like:

res.end('The next target is: ' + finalResult[0].name);

I pulled out the callbacks into separate functions because I found it a bit easier to follow, but I'm sure there are plenty of issues and unnecessary clutter that could be improved. In addition to helping solve my issue, pointers on simplifying the code and tips on better coding practices are welcome! Thanks in advance!

Snake
  • 11
  • 1
  • Thats because nodejs is asynchronous, use [Promises](https://www.npmjs.com/package/promise) or use something to know when your callback has returned – wrangler Nov 26 '17 at 21:09

0 Answers0