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 the console.log(questions)
line should only be hit after the return inside GetQuestions
is hit, however that is not the case.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.