Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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

This is the questions array: [object Promise]

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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()
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!