vaibhav deep
vaibhav deep

Reputation: 835

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.

Upvotes: 2

Views: 324

Answers (1)

turivishal
turivishal

Reputation: 36114

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

Upvotes: 2

Related Questions