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