title: Returning data from mongo within an express.js router function
body: <p>I'm attempting to write a simple validation function that takes a mongo_id and checks to see if it exists. I am able to go this far, but I'm not able to pass that result back to the route that calls the function.</p>
  
  <p>Here is that function which is based on an example that is floating around... It does work.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>validateUserId = function(userId) {
  
    var MongoClient = require('mongodb').MongoClient;
    var assert = require('assert');
  
    var options = {
      mongos: {
        ssl: false,
        sslValidate: false,
      }
    }
    isValid = false;
    MongoClient.connect(vars["MONGO_URL"], options, function(err, db) {
      assert.equal(null, err);
      var q = db.collection("users").find({
        _id: userId
      }, {
        _id: 1
      }).toArray(function(err, record) {
        assert.equal(null, err);
        record.forEach(function(r) {
          console.log(r);
          if (r._id == userId) {
            isValid = true;
          }
        });
        db.close();
        return isValid;
      })
    });
    return isValid;
  
  };</code></pre>
  </div>
  </div>
  </p>
  
  <p>This function does not return anything.</p>
  
  <p>How do I properly modify this code to return a true/false value based on the result of the query?</p>
  
  <p>The idea is to not have to put this code into every route where the validation needs to occur and simply call validateUserId() before performing other tasks (which does not require access or connection to the mongodb.) </p>
  
  <p>Ex:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>app.get("/performVerifiedAction",function(req,res){
   if(validateUserId(req.query['userId'])){
    res.send("You may pass");
   }else{
    res.send("Can't figure out who you are");
   }
   return true;
  });</code></pre>
  </div>
  </div>
  </p>