Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda