Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
<p>The index.js file:</p>

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

function validCheck (exp,name) {
    return exp.test(name);
}
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index');
});

var user=db.collection('user'); //gives reference error,db is not defined

router.post('/',function(req,res,next){
    username=req.body.username;
    password=req.body.password;
    //var user=db.collection('user'); //works fine
    user.findOne({'username':username,'password':password},function(err,docs){
        //do something
    });
});

module.exports = router;
</code></pre>

<p>When using <code>var user=db.collection('user')</code> outside <code>router.post</code>, it gives the error but when the same is used inside <code>router.post</code>, it works fine.</p>

<p>what might be the concept I am missing here?<br></p>

<p><strong>Edit: part of App.js file involving mongodb</strong></p>

<pre><code>var mongodb= require('mongodb');
var MongoClient= mongodb.MongoClient;
var URL = 'mongodb://127.0.0.1:27017/mainDB';

MongoClient.connect(URL,function(err,database){
  if(!err){
    db=database;
  }
  else{
    //do something
  }
});
</code></pre>