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.
Here is that function which is based on an example that is floating around... It does work.
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;
};
This function does not return anything.
How do I properly modify this code to return a true/false value based on the result of the query?
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.)
Ex:
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;
});