'Filter from array of Id's MongoDb data

this is a throw away project just for practice manipulating data from mongoDb. I am trying to filter the existing elemnts from an array of id's:

// filter mongo data from array of id's

const ides = [
  "61f20a5ea86d68cddaaf4207",
  "61f82139abe2f2236f0b65c3",
  "61f8213dabe2f2236f0b65c5",
  "61f82140abe2f2236f0b65c7",
];

const getItems = async (items) => {
  const getDataFromMongo = async (id) => {
       const productDetails = {};
       const product = await Product.findOne({ _id: id });
      
      (productDetails._id = product._id),
      (productDetails.name = product.name),
      (productDetails.price = product.price),
      (productDetails.description = product.description),
      (productDetails.image = product.image),
      (productDetails.category = product.category),
      (productDetails.company = product.company),
      (productDetails.colors = product.colors),
      (productDetails.inventory = product.inventory),
      (productDetails.averageRating = product.averageRating),
      (productDetails.numOfReviews = product.numOfReviews),
      (productDetails.user = product.user),
      (productDetails.createdAt = product.createdAt),
      (productDetails.updatedAt = product.updatedAt),
      (productDetails.__v = product.__v),
      (productDetails.id = product.id);

    return productDetails;
  };
  const item = items.map(async (element) => await getDataFromMongo(element));
  return item;
};
//============================================================================

endpoint looks like this:

  exports.getAllProducts = async (req, res) => {
  const product = await Product.find({}).populate("reviews");
  const data = await getItems(ides);
  console.log(data);

the outpot of the data log is :
[
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]
  res.status(StatusCodes.OK).json({ data: product, others: data });


I think i am missing an await somewhere and the promise does not get resolved, but i just can't figure out where ..



Solution 1:[1]

map runs synchronously returning the array of promises produced by the awaits. The function being mapped produces its own promises. Just resolve them with Promise.all...

const promises = items.map(getDataFromMongo);
return Promise.all(promises);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danh