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
JavaScript
x
19
19
1
//Database connection
2
const MongoClient = require('mongodb');
3
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";
4
5
async function GetQuestions() {
6
MongoClient.connect(uri, async function (err, client) {
7
const db = client.db("WhatSportWereYouMadeFor");
8
return await db.collection("Questions").find().toArray();
9
10
});
11
}
12
13
async function main(){
14
let questions = await GetQuestions();
15
console.log(questions);
16
}
17
18
main();
19
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:
JavaScript
1
19
19
1
const MongoClient = require('mongodb');
2
const uri = "mongodb+srv://user:password@cluster0-10soy.mongodb.net/test?retryWrites=true&w=majority";
3
4
async function GetQuestions() {
5
return new Promise((resolve, reject) => {
6
MongoClient.connect(uri, function (err, client) {
7
const db = client.db("WhatSportWereYouMadeFor");
8
resolve(db.collection("Questions").find().toArray());
9
});
10
});
11
}
12
13
async function main(){
14
let questions = await GetQuestions();
15
console.log(questions);
16
}
17
18
main();
19