Adding elements to an array

router.get("/api/cart", auth, async (req, res) => {
  try {
    const user = await User.findById(req.user._id);
    items = [];
    await user.cartProducts.forEach(async (product) => {
      var item = await Item.findById(product._id);
      items.push(item);
      console.log(items);
    });
    console.log(items)
    res.send(items);
  } catch (e) {
    res.status(500).send(e);
  }
});

I am retrieving the products selected by the user and sending them back in an array. The first console log displays the array with the products, but the second one shows an empty array. The API is functioning correctly without any issues. I suspect that the problem lies in my understanding of JavaScript concepts.

Answer №1

To solve the issue where <code>await
does not work with .forEach, it is recommended to utilize a for loop:

items = [];

for(let product of user.cartProducts) {
   let item = await Item.findById(product._id);
   items.push(item);
}
console.log(items)
res.send(items);

UPDATE:

Additionally, this approach could potentially strain your database. If you require fetching 100 products, you would be making 100 separate requests to the DB.

There is an alternative method to achieve the same outcome in a more efficient manner:

const ids = user.cartProducts.map( p => p._id ); // Array of _id

const items = await Item.find({
    _id : {
         $in : ids
    })
    .lean() // Returns simple JSON, faster

Answer №2

Here's a helpful tip for you on how to manage selected values:

$(document).ready(function () {

  var selectedValues = [];
  
  $("input[name='checkbox']").change(function() {
  var value = $(this).val();
    if ($(this).is(':checked')) {
      selectedValues.push(value);
    }else{
    selectedValues.splice($.inArray(value, selectedValues),1);
    }
  });
 
  $('#button').on('click', function () {
        alert(selectedValues);
  });
  
});
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

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

Having trouble with my code that counts the frequency of elements in an array

I have been struggling to accurately determine the frequency of elements within an array. Despite finding numerous programs online that claim to do this with ease, I have yet to find one that works correctly for my specific array. Below is the code I have ...

Displaying arrays in tabular and grid formats using PHP

I am working with an array containing item code, item name, and price details. $arr = array( "101: orange juice - 5.2", "504: hot roll - 6.2", "106: lime juice - 3", "210: mineral water (s) - 2.6", "107: PEACH JUICE - 6.99", "211: ...

Reordering React Lists: Showcasing the Latest Addition on Top

I'm currently working on a React list and keys project. I want the latest item added to appear at the top. Can anyone offer some assistance with this? For example: import { useState } from "react"; function ListsKeys() { const [names, set ...

Tips for successfully uploading FormData files using Axios: Resolving the TypeError of "file.mv is not a function"

When transmitting a file from one server to another using Axios, I am facing an interesting scenario where one server is an app backend and the other is a blockchain server. The destination for the file transmission is set up as follows: router.post("/a ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

Retrieve the complete HTML content of a webpage, including the values of all input fields

I'm attempting to save the entire webpage as an HTML file, including all previously entered values in input fields. I have already tried this method: $("#content").html(); However, it does not retain the values entered into input fields. $("#conten ...

Issue with AngularJS: Local storage not saving updated contenteditable data

My local storage implementation stops working when I attempt to incorporate contentEditable feature. Here is the link to the CodePen for reference: https://codepen.io/zanderbush/pen/WNwWbWe. Any assistance would be greatly appreciated. The functionality w ...

How can you determine when a download using NodeJS HTTPS.get is complete?

Currently, I am facing an issue while downloading a file. My goal is to perform an action immediately after the download is complete. Specifically, I aim to import a .js file as soon as it finishes downloading. var request = https.get('https://m ...

Can a local image be incorporated into an HTML or CSS project through the use of Javascript or alternative methods?

I've been trying, but all I can manage is: <img width='220' height='280' src='chrome-extension://okjaohhbffepkcfacapapdhkmnebgiba/johnny.jpg' class="me"/> Unfortunately, this code only works in Chrome. Is there a ...

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

Sending a response in the catch block based on conditions

I am currently working on finding the correct method to handle a potential bad Fetch response. My goal is to immediately send a 500 response and halt the code execution if the Fetch response is not okay. However, if the response is acceptable, I need to ...

The color of active links in TailwindCSS remains unchanged

In my project, I am using NextJS along with Tailwind CSS to create a top navigation bar. My goal is to change the text color for active links within the navigation bar. Below is the code snippet I have implemented: const Header = () => { return( ...

After refreshing the page, Google Chrome finally displays the CSS styles correctly

I'm currently working on a JavaScript script to showcase images on a webpage. These images are loaded using an AJAX request and a CSS style is directly applied using jQuery. The script functions correctly on Firefox, Opera, and IE, but Google Chrome i ...

One way to incorporate if / else if statements into a function within a Class component is by using conditional logic in React alongside Node and Express

I'm looking to refactor my code and extract the if/else if statements for error handling out of the component. How can I export this logic to another file and then import it back into my main component? Here's an example of the code: // PASSWOR ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Can you declare an array with a specific size in Kotlin only through initialization?

I am struggling to find a way to declare an array in Kotlin with a predefined size without initializing it. One way to do it is by using: lateinit var v:Array<Int> However, it seems like specifying the size directly in the array type is not allowe ...

Can I retrieve the element of any DOM element I'm currently hovering over using JavaScript?

Suppose I have this HTML snippet: <body> <div id="1"> <span class="title">I'm a title!</span> </div> <div id="2">I'm the first element!</div> <div ...

Using jquery to update a link when a different link is clicked

Recently, I've started using JQuery and encountered a challenge. When I click on the first link, an Ajax request is sent to the server and data is received successfully. However, in the callback function, I'm struggling to change the display text ...