title: MongoDB get the number of documents (count) in a collection using Node.js
body: <p>I'm currently writing a function that should return the number of documents from a collection the thing is that when i'm returning the value it says undefined, Here is my code:</p>
  
  <pre><code>    var MongoClient = require('mongodb').MongoClient;
  
  
  // open the connection the DB server
  var dbName = "ystocks";
  var port = "27017";
  var host = "localhost";
  var tt = "mongodb://" + host + ":" + port + "/" + dbName;
  //"mongodb://localhost:27017/ystocks"
  function getNumOfDocs (collectionName, host, port, dbName) {
      var tt = "mongodb://" + host + ":" + port + "/" + dbName;
      count = 0;
      MongoClient.connect(tt, function (error, db){
  
          if(error) throw error;
          collectionName = collectionName;
          db.collection(collectionName).count({}, function(error, numOfDocs){
              if (error) throw error;
  
              //print the result
              console.dir("numOfDocs: " + numOfDocs);
              count = numOfDocs;
              console.log("count is : " + count);
  
              // close the DB
              return numOfDocs;
              db.close();
  
  
          });// end of count
  
      }); // Connection to the DB
      //return count;
  
  } // end of getNumOfDocs
  
  
  var ee = getNumOfDocs ("stocks", "localhost", "27017", "ystocks");
  console.log("ee is " + ee);
  </code></pre>
  
  <p>Please help me.</p>