Home > Enterprise >  Returning result of mongodb query, and exporting with node
Returning result of mongodb query, and exporting with node

Time:08-04

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?

CodePudding user response:

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()
};
  • Related