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

102
Views
Devolviendo el resultado de la consulta mongodb y exportando con el nodo

Estoy intentando exportar el resultado de una colección MongoDB usando

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

Luego hago referencia a este retorno e intento representarlo en un archivo de jade.

 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}); });

Sin embargo, solo devuelvo un [objeto de promesa]. Por ejemplo, el registro de mi consola devuelve

 This is the questions array: [object Promise]

¿Cómo haría para enviar la matriz a mi archivo de jade desde mi archivo original?

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

0

Acaba de confundir un poco su sintaxis, le recomiendo que lea sobre Promesas y cómo usarlas correctamente, la forma más fácil con su sintaxis actual es envolverla con una promesa:

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

Entonces solo tienes que esperarlo:

 var questionsArray = mongoDAL.getAllQuestions()

El código podría limpiarse usando la sintaxis async/await await en lugar:

 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!