简体   繁体   English

如何循环遍历 mongoose id 数组以检查它是否有效并且它确实存在于数据库中,然后推送到一个新数组

[英]How do I loop through an array of mongoose id to check if it's valid and it does exist in the DB then push to a new array

The function loops through an array from the request body and checks if the productId property is valid if it's valid I push to a new array existingProductId, but it ends up returning an empty array.该函数遍历请求正文中的一个数组,并检查 productId 属性是否有效,如果它有效我推送到一个新数组existingProductId,但它最终返回一个空数组。 Please any ideas or solution.请任何想法或解决方案。

 function returnValidId(products){
 var existingProductId = [];
 products.map(async(product)=>{
 const existingProduct = await Product.findById(product.productId)
 if(existingProduct){
  existingProductId.push({id:existingProduct._id})
 }
 })
 return existingProductId;
 }
 const data = returnValidId(products)
 console.log(data)

You are using .map and you are returning promises, but you are not waiting the resolve of those promises and the function returns the empty array.您正在使用 .map 并且正在返回 Promise,但您并没有等待这些 Promise 的解决,并且该函数返回空数组。 Try:尝试:

async function returnValidId(products){
  var existingProductId = [];
  await Promise.all(products.map(async(product)=>{
    const existingProduct = await Product.findById(product.productId)
    if(existingProduct){
      existingProductId.push({id:existingProduct._id})
    }
  }));
  return existingProductId;
 }
 const data = await returnValidId(products)
 console.log(data)

With Promise.all you are waiting for the promises to be resolved.使用 Promise.all,您正在等待承诺得到解决。

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

相关问题 NodeJS, Mongoose 如果 ID 存在则什么都不做,如果不存在则将新的推入数组 - NodeJS, Mongoose if ID exists do nothing, if doesn't exist push the new one to the array 如何在create方法中将推送数据添加到Mongoose DB中的数组? - How to I add push data to an array in Mongoose DB on create method? 如何查询数组中的ID? 猫鼬 - How do I query an Id in an array? Mongoose 如何使用猫鼬将数组中的数组推入数组? - How do I push to an array within an array in a collection with mongoose? 猫鼬:如何遍历包含对象引用(_id)的数组 - mongoose: how to loop through an array containing object references (_id) 我想遍历一个项目以创建一个数组,然后将其存储在数据库的数组字段中。 我该怎么做? - I want to loop through an item to create an array then store it in array field in the DB. How do I do it? 如果文档的 _id 已经存在,如何将数组元素推送到数组,如果 _id 不存在,如何创建新文档? - How to push array elements to an array if _id of documents already exists and create new document if _id doesn't exist? 如何使用 mongoose 在 MongoDB 的数组中推送数据 - How to push data in MongoDB's array with mongoose 猫鼬:将数据推入数组以进行循环 - Mongoose: Push data to array in for loop ZCCADCDEDB567ABAE643E15DCF0974E503Z如何推送到数组 - Mongoose how to push to array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM