title: Waiting for async "findOne" to finish before returning value
body: <p>I have a file called extrafunctions.js that exports functions to be run by app.js. One of these functions includes the MongoDB query findOne. The problem is that the function returns a value before the query finishes and thus app.js doesn't get the needed data but instead "undefined".</p>
  
  <p>I have tried Promises to some extent but haven't been able to get anything to work.</p>
  
  <p>app.js:</p>
  
  <pre class="lang-js prettyprint-override"><code>const extraFunctions = require("./extraFunctions");
  app.get('/api/login', (req, res) =&gt; {
      res.end(extraFunctions.login());
  });
  </code></pre>
  
  <p>extraFunctions.js:</p>
  
  <pre class="lang-js prettyprint-override"><code>function login () 
  {
  client.connect(err =&gt; {
      var collection = client.db("site").collection("test");
      collection.findOne({}, (err, result) =&gt; {
          if (err) throw err;
          console.log(result);
          return result;
  
      });
      client.close();
  }); 
  }
  
  module.exports.login = login;
  </code></pre>
  
  <p><strong>Fixed Version</strong>
  Same as the accepted comment but had to change <code>res(result)</code> to <code>res(JSON.stringify(result))</code></p>