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

90
Views
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 answers
Answer question

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