[英]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.