Performing numerous queries in MongoDB (using Mongoose) prior to sending back a JSON response

I'm developing a MERN application that involves a one-to-many many-to-many relationship between Users and Organizations. Currently, I am working on creating a function that retrieves all the organizations a user is affiliated with.

Within my routes folder, I have implemented

export const getOrganizations = async (req, res) => {
  try {
    const currentUser = await User.findById(req.user.id)
    
    let organizations = [];
    await currentUser.organizationIds.forEach(async orgId => {
      let organization = await Organization.findById(orgId);
      console.log(organization)
      organizations.push(organization);
    })
    console.log("ORGS")

    res.status(200).json(organizations);
  } catch (error) {
    console.log(error);
    return res.status(500).json({
      message: error.message
    });
  }
}

I believe that incorporating await and async is crucial to resolving the issue at hand. Presently, my console output of "ORGS" appears before displaying the organizations in my forEach loop. Nonetheless, I am uncertain about the exact steps required to rectify this situation.

Answer №1

The issue lies in the asynchronous callback within the forEach function. To solve this, consider using a for loop instead to properly utilize await without skipping ahead while waiting for the asynchronous code to complete. For example:

for(let i = 0; i < currentUser.organizationIds.length; i++) {
   let organization = await Organization.findById(currentUser.organizationIds[i]);
   console.log(organization)
   organizations.push(organization);
}

Alternatively, you can use the map function to store all promises in an array and then utilize Promise.all to ensure they all finish before proceeding. Example:

const fetchOrg = async orgId => {
  let organization = await Organization.findById(orgId);
  console.log(organization)
  organizations.push(organization);
}
let promises = currentUser.organizationIds.map(orgId => fetchOrg(orgId))
await Promise.all(promises);

Answer №2

It seems that in the User model, there is a property called organizationIds which holds an array of ObjectIds referencing the Organization schema, defined as follows:

organizationIds: [{type: mongoose.Schema.Types.ObjectId, ref: 'Organization' }]

If this is the setup, you can easily use the populate method to populate the organizationIds property:

export const getOrganizations = async (req, res) => {
  try {
    const currentUser = await User.findById(req.user.id).populate('organizationIds');
    
    res.status(200).json({organizations: currentUser.organizationIds});
  } catch (error) {
    console.log(error);
    return res.status(500).json({
      message: error.message
    });
  }
}

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

Using gulp to compile TypeScript is resulting in a directory being generated that we do not want

My goal is to use Gulp to transpile my .ts files located in the /dev directory, and then move the transpiled .js file to a /build directory. The ideal folder structure I am aiming for is as follows: /dev - index.ts /build - index.js However, the curre ...

"The powerful trio of Moongose, expressjs, and node-webkit combine forces

I'm currently in the process of developing an app using node-webkit, with expressjs and mongoose as the foundation. As a newcomer to this technology stack, I've encountered some challenges. One specific issue involves my attempt to integrate a m ...

What is the method for dividing a string using capital letters as a delimiter?

I am currently faced with the challenge of splitting a string based on capital letters. Here is the code I have come up with: let s = 'OzievRQ7O37SB5qG3eLB'; var res = s.split(/(?=[A-Z])/) console.log(res); However, there is an additional re ...

Using Meteor: The ultimate guide to filtering data with a session variable

I have three buttons that display different types of information View all (i.e., news AND events) news only events only Status: Filtering ONLY news OR events works. But how can I view both? My problem lies in writing a MongoDB query in combination with ...

The cURL command successfully executes the request, however, it fails to work in both Postman and web browsers

A problem arises when the Node Js (express) server responds to requests using cUrl, resulting in an infinite load. However, when requested via Postman or a browser, there are no errors but still faces issues. Despite searching for solutions, none of the s ...

Unveiling the Secret: How to Incorporate Tooltips into Flexigrid Table Cell Data

I have implemented tooltips for table headers by using the following code snippet in the flexgrid.js file within the column model iteration: if (p.colModel) { thead = document.createElement("thead"); var tr = document.createElement("tr"); ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Ensure to close the window prior to loading Angular modules following successful authentication

One approach I'm exploring is having users authenticate with Facebook in a separate window to eliminate the need for refreshing the web app. The current setup involves redirecting the user to a route that contains an HTML file which includes a script ...

Manipulate audio files by utilizing the web audio API and wavesurfer.js to cut and paste audio

I am currently working on developing a web-based editor that allows users to customize basic settings for their audio files. To achieve this, I have integrated wavesurfer.js as a plugin due to its efficient and cross-browser waveform solution. After prior ...

Jquery vertical menu with a dynamic sliding animation from the right side to the left side

Hello everyone, I am looking to have my vertical menu slide from right to left instead of the typical top to bottom sliding that comes with using .toggle() in jQuery. Specifically, when the hamburger menu is clicked, I want the menu to slide out from right ...

Is there a way to prevent routes from a specific source using cors and expressjs?

I am currently using cors to only allow requests from a single origin to access ANY ROUTE. However, I now need to modify it to also block certain routes for that same origin. If there is a way to achieve this, please provide your answer. Thank you. This i ...

Having difficulty retrieving keys from a JSON object returned by a mongoose findOne() query

Recently, I've come across a strange issue. I used mongoose to search for a document in my mongoDB using model.findOne() with the following code: Model.findOne({ ID: ID }).then(existingDoc => { console.log(existingDoc ); res. ...

Utilizing node http for transmitting and receiving simple text messages instead of complex objects

I'm a novice when it comes to working with webservers, and I've hit a roadblock while attempting to send data from a JavaScript script on a website to a locally running server. The communication between them is established, but the data received ...

Tips for displaying the initial slide when a tab is loaded on a multi-tab webpage

I have a total of four tabs, with the first tab containing a slideshow. On page load, I am successfully triggering the first tab, but for some reason, the first slide in the slideshow within that tab is displaying a blank image. I'm struggling to find ...

Utilizing ExtJS: Defining default settings for panel items within nested objects

This particular question is part of a discussion regarding How to set defaults for Grid columns within initComponent. It has been shared here independently as per the advice given by @scebotari66 in the main post. Below, you can see the use of Ext.Array.m ...

Working with SASS imports in an isomorphic React app: best practices

Currently, my React app is set up with SSR support as follows: React app Express server that compiles the React app using webpack Using babel-node to run the Express app with ES6 features Everything works fine until I added CSS modules to the React app, ...

How can Grails send the edited object from a form within a template using AJAX?

I am looking to dynamically update a field in an edit form based on changes made to another field. The idea is that when field1 is modified, an AJAX script will call the controller to calculate a new value for field2 and then update the template accordingl ...

Determine the array with the highest value by comparing multidimensional arrays in JavaScript

I have a multidimensional array with names and corresponding integer values. I want to compare the integer values within each nested array to find and return the one with the highest value. var nums = [ ['alice', 'exam', 60], [ ...

Generating an array in Javascript using JSON

I've been doing a lot of research, but I can't seem to find a solution that works for me. My goal is to retrieve the next four bus arrival times for a specific bus stop using an application that reaches out to an API returning JSON data. The issu ...

A windows application developed using either Javascript or Typescript

Can you provide some suggestions for developing Windows applications using Javascript, Typescript, and Node.js? ...