Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application.

app.get("/admin/orders", (req, res) => {
  Quote.find({}, (err, quotes) => {
    var products = [];
    var users = [];
    quotes.forEach((quote) => {
      User.findOne({ email: quote.user }, (err, user) => {
        if (!err) {
          users.push(user);
        }
      });
    });
    res.render("orders", { quotes: quotes, users: users, products: products });
  });
});

Despite not receiving any errors from the database and successfully retrieving my users, when trying to log the array I am getting an empty result.

Answer №1

When faced with a similar issue in my express project, I came up with a clever solution that did the trick. By adding an index counter inside the loop, I was able to get everything working smoothly:

app.get("/admin/orders", (req, res) => {
  Quote.find({}, (err, quotes) => {
    var products = [];
    var users = [];
    quotes.forEach((quote, index) => {
      User.findOne({ email: quote.user }, (err, user) => {
        if (!err) {
          users.push(user);
        }
        if (index+1 == quotes.length)
        {
            return res.render("orders", { quotes: quotes, users: users, products: products });
        }
      });
    });
    
  });
});

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

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

"Troubleshooting: Issues with message passing between popup.html and content.js in Chrome Extension

I'm facing a challenge in creating an Extension that transfers data from popup.html to the tab dome. Unfortunately, I am having trouble with getting the sendMessage function to work and I can't figure out why. I'm using the following guideli ...

Updating the value of a Redux-Form Checkbox Field using programming methods

I have created a registration form where users can accept or decline the terms of services. When a user accepts the terms, they click a button to check the checkbox. If they decline, the button will uncheck the checkbox. https://i.sstatic.net/mfkcY.png ht ...

What is the best way to efficiently input identical data into multiple controllers ($scope) using just one call in AngularJS?

I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working! Here is the code snippet: (function ...

Using environment variables in next.config.js allows for successful connection to the database, however, when attempting to use a

Utilizing the serverless-mysql library, I have successfully connected my next app to a remote MySQL DB through an SSH tunnel with the ssh2 library. Although everything is functioning properly, I am looking to enhance the security of my code by removing the ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

Looking for tags similar to stackoverflow?

Is there a way to create a search box similar to the one in Tags where tag names are displayed immediately upon entering without pressing enter key? Could anyone provide me with a script or tutorial on how to achieve this? Is it done using JavaScript or j ...

Click the button to instantly scroll to a particular word with highlighting, and with another click, jump to the next occurrence

In order to achieve the objective, simply click on a button that will search for and scroll to a specific word while highlighting it. The same button can be clicked again to find the next occurrence, and so on. If you need an example of how this works, ch ...

What is the best approach for extracting JSON data (using jQuery) from Google Geocoding services?

Obtaining the city name using latitude and longitude is my current challenge. Google Geocoding offers a helpful solution known as "Reverse geocoding". According to the documentation, a GET request needs to be made to the following link: http://maps.googl ...

Issue with JQuery addClass functionality in Firefox

I've come across numerous posts on this topic, but none of them have provided a solution. I recently added drag and drop functionality to my website. When I drag an item over a valid container, I add a specific class to it. Here is the HTML for the ...

Combining GET and POST requests in ExpressJS on a single route

As I work on setting up a questionnaire in Express JS with EJS as the renderer, I have already created individual pages for each question. These pages are accessible through static links using the app.get('/question/:number?', routes.questions) f ...

Encountering an H12 error while trying to deploy a Node.js Express MongoDB application on Heroku

The Challenge Greetings everyone, I am currently facing a dilemma after deploying my Node.js Express and MongoDB application to Heroku. While the app works perfectly on my local machine, I encountered an H12 error in the Heroku logs. Here is the exact err ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

Why is the promise not returning an integer value, but instead returning undefined?

My validation process includes checking the integrity of the down streaming data to the server and verifying its existence in the database. The code snippet from model.js: const mongoose = require('mongoose'); const User = new mongoose.Schema({ ...

Struggling to understand the process of creating a new page in Express

I've created a file called ships.js in my routes folder: var express = require('express'); var router = express.Router(); /* GET Ships page. */ router.get('/ships', function(req, res, next) { res.render('ships', { tit ...

What is the best way to update an existing cookie value using angularjs?

Currently, I am working with AngularJS. When a button is clicked, I am setting a cookie and it works perfectly fine. However, when the page is refreshed and another button click occurs, a new value is stored in the array while the old cookie value becomes ...

Attempting to retrieve and save data in a variable using React Native

click here for image referenceI am a beginner in react-native and I recently attempted to use fetch to access an API. While I successfully managed to print the result on the console, I encountered difficulty in displaying it on a mobile screen. Below is a ...