Facing problem with scope in mongoose
User.findById(req.user.id, (err, result) => {
var cartProduct = [];
result.cart.map(async (item) => {
//item is {
productId: "product-id",
quantity: "2"
//}
const product = await Product.findOne({ productId: item.productId });
cartProduct.push(product); //stores
});
console.log(cartProduct); //empty
});
Please help me
Problem is that you map the result.cart
items to async functions but you never actually await
them.
Try the following:
User.findById(req.user.id, (err, result) => {
var cartProduct = [];
await Promise.all(
result.cart.map(async (item) => {
//item is {
productId: "product-id",
quantity: "2"
//}
const product = await Product.findOne({ productId: item.productId });
cartProduct.push(product); //stores
})
);
console.log(cartProduct); //empty
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.