title: TypeError: Cannot read property 'collection' of undefined
body: <p>I am new in nodejs and currently working on node.js and mongodb.This my mongodb connection code</p>
  
  <pre><code>var mongodb = require("mongodb");
  
  var MongoClient = mongodb.MongoClient;
  
  var url = 'mongodb://localhost:27017/mydb';
  
  var mongodbStore = {};
  
  var db;
  
  MongoClient.connect(url, function (err, dataBase) {
      if (err) {
          console.log('Unable to connect to the mongoDB server. Error:', err);
      } else {
  
          debug("Connected to mongodb. Initialising saved listeners...");
          db = dataBase;
          var manager = require('./managers/manager');
      }
  });
  
  mongodbStore.add = function(name, data) {
      var collection = db.collection('listeners');
  
      if (collection) {
          collection.insert("listener", JSON.stringify(data));
      }
  };
  </code></pre>
  
  <p>I will call "add" function from my another file.But now I am getting Error on first line in add function</p>
  
  <pre><code>var collection = db.collection('listeners');
  </code></pre>
  
  <p>Error is:</p>
  
  <pre><code>TypeError: Cannot read property 'collection' of undefined
      at Object.mongodbStore.add (C:\Node.js Listeners 2\mongodbStore.js:54:21)
      at C:\Node.js Listeners 2\managers\manager.js:46:18
      at Server.&lt;anonymous&gt; (C:\Node.js Listeners 2\managers\tcpManager.js:54:10)
      at Server.emit (events.js:104:17)
      at net.js:1171:12
      at process._tickCallback (node.js:355:11)
  </code></pre>
  
  <p>Can any one please tell me,What is wrong here and what is correct way?</p>