I\'m not sure what I\'m missing here. I would like to query a MongoDB Database within a Nodejs function. The jobs
variable below, keeps returning undefined. I\'
client.connect
is async
function and accepts callback. You cannot access the jobs
variable outside the callback scope.
To do so you can wrap the client.connect
method into a function and can return promise from there.
async function getDataFromMongoDB(page) {
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb://localhost:3001";
const client2 = new MongoClient(uri, { useNewUrlParser: true });
const client = await connectToMongodb(client2)
const collection = client.db("meteor").collection("jobs");
const jobs = await collection.find().toArray();
console.log("jobs", jobs);
}
connectToMongodb(client) {
return new Promise((resolve, reject) => {
client.connect(function(err) {
return resolve(client)
});
})
}