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

211
Views
Koa no está esperando la respuesta de MongoDB y devuelve nulo en respuesta

Estoy creando una aplicación para el cliente. y estoy usando koa.js mongodb (para la base de datos) en la aplicación. Estoy tratando de obtener detalles de los clientes con recordatorios totales con clientes específicos, pero koa no espera la promesa y devuelve "[]" en respuesta cada vez que intento llamar esa ruta

aquí está mi código

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

y esta es la imagen de respuesta cuando llamo a esta ruta:

ingrese la descripción de la imagen aquí

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

0

Pruebe Promise.all en lugar de la nueva 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 Report

0

Tienes un montón de cosas extra allí.

¿Cuál es la idea detrás de esto?

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

Si esta parte remind_col.find({}).toArray() devuelve una matriz, ¿por qué está colocando dentro de la matriz y luego obteniendo el primer elemento?

Creo firmemente que simplemente puede usar esto a continuación

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

Dado que no es un middleware, no necesita asignar nada al objeto de contexto.

Definiste promesa pero nunca resolviste un valor.

Limpio un poco tu código y asumo que esto funcionaría para ti.

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