Implementing a restricted Mongoose promise loop iteration count

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) });
};

Answer №1

Knowing the exact number of items you are interested in can optimize your database query by using .limit(quantity) to only fetch the desired quantity, as shown below:

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

    Item.find({productId: productId, userId: null})
        .limit(quantity) // <--- Ensure to add this line
        .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) });
};

This method reduces memory consumption by fetching only the necessary elements from the database and updating the correct number of items.

Answer №2

If you're looking to update items in an array before mapping over them, one simple approach is to first slice the array to the desired size. Below is an example code snippet with async/await syntax:

await Promise.all(items.slice(0, quantity).map(async (item) => {
    return item.update({userId: req.userId});
}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

Add fresh material to the bottom of the page using Javascript

Hey there, I'm having a bit of trouble with my page where users can post their status. I want the new posts to appear at the bottom after the older posts when the user presses the button. Currently, Ajax is placing all new posts at the top of the old ...

Guide on retrieving information from MySQL database and showcasing it in a form through AJAX

I have developed a form that is designed to automatically populate the fields for first name and last name with data from mysql when the user enters their user_id. My approach involves using ajax to retrieve the data, which works fine as I am able to fetch ...

Transitioning to Meteor and React or Immigrating to Meteor

Are there any available resources specifically designed for Meteor that can assist with loading large assets (ranging from 20MB to 80MB) primarily for offline use? Currently, I am working on a project using Vanilla JS on the client side, but I am contempl ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Implementing image rendering functionality in Vue.js

So here's what's going on: I developed a horror movie bucket list app for my bootcamp final project. The minimum viable product received positive feedback, and I obtained my certification. However, now that I've graduated, I want to enhance ...

Verify if the button is assigned a specific class, then generate a 'completed' div

I'm new to working with Jquery and I have a question. In my upload form, when something is uploaded the upload-button changes class from: <a class="upload-button upload buy" id="upload-button"><span>Upload a document</span></a> ...

Is SSG the best approach for deploying a Nuxt.js dashboard?

We have plans to create an internal dashboard utilizing Nuxt.js. Since this dashboard will be used internally, there is no requirement for a universal mode. Typically, most dashboards are designed as SPAs (Single Page Applications). However, SPAs still ne ...

Capturing the dynamic server response with nested JSON structures

I am in the process of creating a dynamic data-binding function named assemble that requires two input parameters: server response (JSON) - nested JSON object. instruction set (JSON) - a configuration object that dictates the binding. The Issue: The cur ...

Using Vue.js: Passing an object from data() to a mounted() function

I'm facing an issue while attempting to pass the grid array to the createGridChart. An error message stating "grid is not defined" keeps popping up: “grid is not defined”. export default { data() { return { grid: [], } ...

Using the OR operator in an Angular filter

How can I create a filter with a range slider that shows multiple categories when it's in a certain position? I have tried using the code below to filter based on the range, but it only captures the first word after the OR operator. Can anyone provid ...

When I try to access localhost, it directs me to http://localhost:3000/myprofile%20 instead of localhost:/3000/myprofile

Every time I try to log into my profile page with the correct login credentials, I get redirected to http://localhost:3000/myprofile%20, but then receive a 404 error. This is what my code looks like: // Login Route router.post('/login', functi ...

The sendKeys() method in Protractor is failing due to the element being hidden/not

Hi there! I am currently new to automated testing with protractorJS for an angularJS homepage. While the code I've written so far has been successful, I'm facing an issue where I'm unable to input keys into the search field. After running th ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

Initiating a AJAX upload upon selection of a specific option from a select menu

Recently, I have been exploring ways to enhance my layout page by implementing an option for users to upload new logos on the spot. Currently, users are able to choose their desired image through a drop-down selection feature. I am interested in adding a f ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

JavaScript Age Calculator - Counting Days

Hey there! I've got an interesting problem. I currently have three text boxes on my webpage, and what I want to achieve is having a fourth text box generated when the user clicks a button. The content of this new text box should be filled with the dat ...