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

87
Vistas
Pending promise in MongoDB
let comments = await Comment.find({ post })
      .populate({ path: "user", select: "name photoURL role page" })
      .sort({ createdAt: -1 });

    console.log("comments --", comments);
    const pages = [];
    let pagesData = comments.map(async (comment) => {
      let page = await Pages.find({ user: comment.user._id });
      console.log("page", page);
      pages.push(page);
    });

    console.log("Pages -- ", pagesData);

I have this code in which I am trying to get documents from a db. When I log the logs written above, I get expected results for comments and page and not for pages or pagesData.

pagesData log gives me:

Pages --  [
   Promise { <pending> },
   Promise { <pending> },
   Promise { <pending> },
   Promise { <pending> },
   Promise { <pending> },
   Promise { <pending> }
 ]

pages log gives me an empty array as initialized, the results from the query on Pages do not get pushed to the array pages.

However, I get all expected results in individual page logs. How can I add these results to a single data structure? Any help appreciated.

Thanks in advance.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The map function will not give promise you need to use Promise.all method, and console the pages array.

const pages = [];
let pagesData = comments.map(async (comment) => {
  let page = await Pages.find({ user: comment.user._id });
  console.log("page", page);
  pages.push(page);
});
await Promise.all(pagesData);
console.log("Pages -- ", pages);

The above solution will solve the pending promise problem, but this is not a good approach to query in the database in a loop,

You can try the below approach to select all pages by a single query,

  • map to iterate loop of comments and get array of user ids
  • $in to select all user that haveing _id from array
let pages = await Pages.find({ 
  user: { 
    $in: comments.map((comment) => comment.user._id);
  }
});
console.log("Pages -- ", pages);
over 4 years ago · Santiago Trujillo 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