Express js,mongodb: “ReferenceError: db is not defined” when calling a function
<p>The code is set up this way:</p>

<pre><code>var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;

function getData(){
  db.collection("collection_name").find({}).toArray(function (err, docs) {
      if (err) throw err;
      //doing stuff here
      }

      var dataset = [
          {//doing more stuff here
          }
      ];
  });
}

router.get("/renderChart", function(req, res) {
    mongo.connect(url_monitor, function (err, db) {
        assert.equal(null, err);
        getData(res);
    });
});
</code></pre>

<p>When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:</p>

<p><a href="https://stackoverflow.com/questions/34566049/express-js-mongodb-referenceerror-db-is-not-defined-when-db-is-mentioned-out">Express js,mongodb: &quot;ReferenceError: db is not defined&quot; when db is mentioned outside post function</a></p>