Currently, I am developing an online store using Node, Express, and Mongoose. In the postCheckout Controller, which is responsible for handling user purchases, I am facing an issue. When a user buys a product with a quantity of 5, the code should check if there are enough items available and then update the "userId" attribute to the user's id (req.userId) for only 5 items. However, my current implementation updates the userId for all items instead of just 5 because I am unsure how to limit the loop within the promise.
exports.postCheckout = (req, res, next) => {
const productId = req.body.productId;
const quantity = req.body.number;
Item.find({productId: productId, userId: null})
.then(async (items) => {
if (items.length >= quantity) {
await Promise.all(items.map(async (item) => {
// How can I limit this loop to only update the userId for 5 items?
await item.update({userId: req.userId});
}));
}
res.redirect('/orders');
}).catch(err => { return next(err) });
};