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
Koa is not waiting for MongoDB Response and returning null in response

I'm creating a application for client. and I'm using koa.js mongodb(for database) in application.I'm trying to get customers details with total reminders with specific customers but koa is not waiting for promise and returning "[]" in response whenever i try to call that route

here's my code

    router.get("/getcustomers",async (ctx)=>{
      ctx.customers = [await remind_col.find({}).toArray()][0];
      ctx.customeralgo = [];
      new Promise((reso,reje)=>{ 
        ctx.customers.map(async cust=>{
          return {
            email:cust.email,
            first_name:cust.first_name,
            last_name:cust.last_name,

             //------------- This is the when I'm trying to get count for customer
            total_reminders:[await remind_col.count({"email":cust.email})][0],
            //----------------
          }
        })
      }).then(rlt=>{
        ctx.customeralgo = rlt;
        console.log(rlt);
        ctx.body = ctx.customeralgo;
      })

    })

and this is response image when I call this route:

enter image description here

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

0

Try Promise.all instead new Promise

router.get("/getcustomers", async (ctx) => {
  ctx.customers = [await remind_col.find({}).toArray()][0]
  ctx.customeralgo = []
  const promises = ctx.customers.map(async cust => ({
    email: cust.email,
    first_name: cust.first_name,
    last_name: cust.last_name,
    // ------------- This is the when I'm trying to get count for customer
    total_reminders: [await remind_col.count({ "email": cust.email })][0],
    //----------------
  }))
  Promise.all(promises).then(rlt => {
    ctx.customeralgo = rlt
    console.log(rlt)
    ctx.body = ctx.customeralgo
  })
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You have a bunch of extra things there.

What is the idea behind this?

ctx.customers = [await remind_col.find({}).toArray()][0];

If this part remind_col.find({}).toArray() returns an array why you are putting inside array and then getting the first element?

I strongly believe, you can simply use this below

const customers = await remind_col.find({}).toArray();

Since it is not a middleware you don't need to assign anything to the context object.

You defined promise but never resolve a value.

I clean your code a bit and I assume this would work for you

router.get('/getcustomers', async (ctx) => {
  const customers = await remind_col.find({}).toArray();
  const transformedCustomers = customers.map(async (customer) => ({
    email: customer.email,
    first_name: customer.first_name,
    last_name: customer.last_name,
    total_reminders: await remind_col.count({ email: customer.email }),
  }));

  ctx.body = await Promise.all(transformedCustomers);
});
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