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".
I have tried Promises to some extent but haven't been able to get anything to work.
app.js:
const extraFunctions = require("./extraFunctions");
app.get('/api/login', (req, res) => {
res.end(extraFunctions.login());
});
extraFunctions.js:
function login ()
{
client.connect(err => {
var collection = client.db("site").collection("test");
collection.findOne({}, (err, result) => {
if (err) throw err;
console.log(result);
return result;
});
client.close();
});
}
module.exports.login = login;
Fixed Version
Same as the accepted comment but had to change res(result)
to res(JSON.stringify(result))