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!