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

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

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 Relatório

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 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