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

Updating the state of an array containing objects within an array of objects in React

I have a state called invoices, which is an array of objects structured like this: const [invoices, setInvoices] = useState([ { id: 123, tag_number: "", item_amounts: [ { item: "processing", amount: 159 }, { i ...

Is it possible to utilize an if statement to select a specific Bootstrap modal?

How can I make a modal appear when the user clicks select? The first page has radio buttons (e.g. oneway, twoway), and I want the second page to display different fields based on which radio button is selected. Can I use an if statement for this? If so, ...

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

Adding a picture to the webpage and saving it temporarily on the site

After exploring all options on the site, testing it rigorously and closely following the instructions provided, I am still unable to determine where exactly I went wrong. Website Link: The main goal is to upload an image and temporarily store it within t ...

The function socket.to(socket.id).emit() is not functioning as expected

Struggling to implement targeted messaging in socket.io, even with the guidance provided in the documentation. The documentation suggests using socket.to(socket.id).emit('event name', 'message') to send a message to a specific user sock ...

Looking to showcase the outcome of the Procedure invocation when I made the call?

{ "isSuccessful": true, "resultSet": [ { "name": "pradeep", "password": 123, "timestamp": "2014-04-08T12:58:45.000Z" }, { "name": "dileep", "password": 1234, "timestamp": "2014-04-08T13:00:52.000Z" } ] } I have ...

I keep seeing this strange [object HTMLSpanElement] appearing on my HTML page

Thanks for the help, the issue has been resolved and I appreciate your valuable time! ...

Error: The field "key" must be provided

Encountering an error with express-openid-connect TypeError: "secret" is required at module.exports.get (/home/mathkr/persodev/node_modules/express-openid-connect/lib/config.js:166:11) at module.exports (/home/mathkr/persodev/node_modules ...

Retrieve information from a dropdown menu that is dependent on the selected value from another dropdown

   Check out this sample API data - I currently have three dropdown menus set up: From Release To Release Compatibility When a specific from release is selected, all corresponding to releases associated with that specific from release should be displ ...

Retrieving a list of numbers separated by commas from an array

Currently, I'm retrieving data from a MYSQL database by executing the following SQL command: SELECT GROUP_CONCAT(MemberMemberId SEPARATOR ',') AS MemberMemberId FROM member_events WHERE event_date = "2000-01-01" AND Eve ...

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

What are the steps to input text into a textbox on a different domain using my own domain?

Is it possible to input a value into a textbox on a different domain, to which I do not have access, by submitting a form from my own domain? Here is the form on my domain: <form action="" method="post" name="birthdaysend"> <input type="text" v ...

Learn how to extend components in Typescript and determine necessary arguments. Discover how to apply this knowledge in an Angular use case by extending mat-side-nav

Background: The Angular Material Design component known as mat-side-nav operates in a specific structure for its dynamics: <mat-sidenav-container> <mat-sidenav> </mat-sidenav> <mat-sidenav-content> </mat-sidenav-conten ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

Retrieve all the keys from an array of objects that contain values in the form of arrays

Looking for an efficient way to extract all keys from an array of objects whose values are arrays, without any duplicates. I want to achieve this using pure JavaScript, without relying on libraries like lodash or underscore. Any suggestions on how to impro ...

The data retrieved from the API call is outdated

I am struggling with a weather web API that is only showing old data when called in the code. However, when I enter the API URL directly into the browser, it displays the most up-to-date information for the current city. Can anyone help me troubleshoot why ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Creating an Add-in using the Excel JavaScript API based on an already existing spreadsheet

Is there a way to create an Add-in using Excel JavaScript API from an existing spreadsheet? When running npm start, it generates a blank workbook. I believe changes need to be made in the Manifest.xml file, as npm start triggers office-addin-debugging star ...

Encountering JSON error when invoking multiple functions

Encountering JSON Error when calling multiple functions Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0 I've been attempting to call multiple functions in jQuery but keep getting an error. I've tried various soluti ...