Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

72
Views
Node.JS send results after for loop

I have a problem with my Controller in Node.Js First I find all Products related to an outfit and then I loop over all products to get the information related to that. The queries are working but I get the error "Cannot set headers after they are sent to the client" or the body is an empty Array. This is my code.

    const Outfits = require("../models/Outfits");
const Products = require("../models/Products");

module.exports = async (req, res) => {
    Outfits.find({ outfitId: req.params.id }, (error1, result) => {
        if (error1) {
            res.status(400).json({
                status: "fail",
            });
        } else {
            let productIds = result[0].productIds;
            let productsList = [];
            productIds.forEach((id) => {
                Products.find({ id: id }, (error2, products) => {
                    if (error2) {
                        res.status(400).json({
                            status: "fail",
                        });
                    } else {
                        productsList.push(products);
                        console.log(productsList);
                    }
                });
            });
            res.status(200).json({
                status: "success",
                body: productsList,
            });
        }
    });
};

Do you have any suggestions? Thank you!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!