Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning result of mongodb query, and exporting with node

I am attempting to export the result of a MongoDB collection using

exports.getAllQuestions = async function (){
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("Time4Trivia");
        return dbo.collection("Questions").find({}).toArray().then();
      });
};

I am then referencing this return and attempting to render it in a jade file

router.get('/play', function(req, res, next) {
   var questionsArray = mongoDAL.getAllQuestions()
  console.log("This is the questions array: " +  questionsArray)
  
  res.render('play', { title: 'Time 4 Trivia',user: req.session.user, questions: questionsArray});
});

However, I am only returning an [promise object]. For example my console log returns

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is the questions array: [object Promise]

How would I go about actually sending the array to my jade file from my original file?

>Solution :

You just got your syntax mixed up a little, I recommend you go read about Promises and how to use them properly, the easiest way with your current syntax is to just wrap it with a promise:

exports.getAllQuestions = async function (){
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("Time4Trivia");
            return resolve(await dbo.collection("Questions").find({}).toArray())
        });
    })
};

Then you just need to wait for it:

var questionsArray = mongoDAL.getAllQuestions()

The code could be cleaned up using async/await syntax insted:

exports.getAllQuestions = async function (){
    const db = await MongoClient.connect(url);
    var dbo = db.db("Time4Trivia");
    return await dbo.collection("Questions").find({}).toArray()
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading