2019-08-23
How to Mongoose promise loop limit to only few times?
stackoverflow
Question

I'm writing a webshop in Node with Express and Mongoose. When a user buys a product (e.g. quanitity=5), the postCheckout Controller should check if there are enough items and then change the attribute "userId" to the user's id (req.userId) for 5 items. My current code changes the userId for all of the items, because I don't know how to limit the loop to 5 inside the promise.

exports.postCheckout = (req, res, next) => {
    const productId = req.body.productId;
    const quanitity = req.body.number;

    Item.find({productId: productId, userId: null})
        .then(async (items) => {
            if (items.length >= quanitity) {
                await Promise.all(items.map(async (item) => {
                    await item.update({userId: req.userId});
                }));
            }

            res.redirect('/orders');
        }).catch(err => { return next(err) });
};
Answer
1

There are a few ways that you could go about doing this, but I think the simplest would be to slice your items array to the size you want before mapping over the items. Example is below (with slightly cleaned up async/await syntax).

await Promise.all(items.slice(0, quantity).map(async (item) => {
    return item.update({userId: req.userId});
}));
How to Mongoose promise loop limit to only few times?
See more ...