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.