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

216
Vistas
Can't get result from a nodejs module

I wrote a small Javascript module to get rows from a MongoDB database:

async function getAll() {
  await mongoose.connect(config.mongoURL).catch(err => { console.log(err); });
  const conn = mongoose.connection;
  conn.collection('healthdata')
    .find({}).toArray().then(result => {
      console.log('=>Docs:', result);
      return result;
   }).catch (err => {
    console.log(err);
   }).finally(() => {
    conn.close();
   });
}
exports.getAll = getAll

I get the correct display from the console ("=>Docs:"). But, when I want to get the result from the following calling function, I get the Undefined value ("Result:"):

app.get("/", async (req, res) => {
  var docs = await db.getAll().then();
  console.log("Result:", docs);
  res.render("index.html");
 });

What is missing? Wrong?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think the console.log(Result:...) line is executing before your getAll completes.

I would wrap it inside the "then" clause:

app.get("/", async (req, res) => {
  const docsReturned = await db.getAll()
     .then(docs => {
          console.log("Result:", docs);
          res.render("index.html");
     })
     .catch(err => {
          console.error(err);
     }));
     return(docsReturned);

I also suggest adding a catch for any errors...good practices. :)

about 4 years ago · Juan Pablo Isaza Denunciar

0

you should not mix promises with async/await, so either the answer provide by G-Force but remove the await before db.getAll() or use var docs = await db.getAll(); this should solve your problem.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Bro if you are using mongoose follow these to get data from mongoose schema

schema.find().exec().then(result=>{

console.log(result)

}).catch(error=>{

console.log(error)

})

here all schema data in result that we console if any error come it displays in console.log(error)

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