I'm sure I'm missing something very basic around async functions or something, but when I try and access a function in a module the result is not available.
This is the code in the main file, the module is accessed as 'queries'.
app.post('/records', (req,res) => {
const query = req.body.query;
const queryresult = queries.runSearch(query);
res.end(queryresult);
});
The code for runSearch is the following
function runSearch(query){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Connected!");
var dbo = db.db("followers");
dbo.collection("User").find({Bio : {$regex : query}}).toArray(function(err, result) {
if (err) throw err;
console.log("records returned = " + result.length);
var JSONResult = JSON.stringify(result);
db.close();
console.log('db connection closed');
return JSONResult;
});
});
}
module.exports = {runSearch}
I get what's happening is the async Mongo call is working away and not being waited for. I've read everything around async / await but it melts my brain a bit.
Would love to know what it might look like with this code.