Skip to content
Advertisement

Awaiting an async function when using Mongodb in node.js

I am trying to retrieve all documents from a MongoDB cluster. I’ve been searching online and using the async/await keywords and have wrote the following code

//Database connection
const MongoClient = require('mongodb');
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";

async function GetQuestions() {
     MongoClient.connect(uri, async function (err, client) {
        const db = client.db("WhatSportWereYouMadeFor");
        return await db.collection("Questions").find().toArray();

    });
}

async function main(){
    let questions = await GetQuestions();
    console.log(questions);
}

main();

From my understanding of the async/await pattern theconsole.log(questions) line should only be hit after the return inside GetQuestions is hit, however that is not the case.

Advertisement

Answer

You should return a Promise with the result of Mongoose:

const MongoClient = require('mongodb');
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";

async function GetQuestions() {
     return new Promise((resolve, reject) => {
         MongoClient.connect(uri, function (err, client) {
             const db = client.db("WhatSportWereYouMadeFor");
             resolve(db.collection("Questions").find().toArray());
         });
     });
}

async function main(){
    let questions = await GetQuestions();
    console.log(questions);
}

main();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement