简体   繁体   English

从 Id 的 MongoDb 数据数组中过滤

[英]Filter from array of Id's MongoDb data

this is a throw away project just for practice manipulating data from mongoDb.这是一个一次性项目,仅用于练习从 mongoDb 操作数据。 I am trying to filter the existing elemnts from an array of id's:我正在尝试从 id 数组中过滤现有的元素:

// 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..我想我在某处错过了等待,promise 没有得到解决,但我就是不知道在哪里..

map runs synchronously returning the array of promises produced by the awaits. map同步运行,返回等待生成的承诺数组。 The function being mapped produces its own promises.被映射的 function 产生了自己的承诺。 Just resolve them with Promise.all...只需用 Promise.all 解决它们...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM