Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda