DEV Community

sm-a
sm-a

Posted on

1

How can I use mongoose first with mongoose find, then with forEach loop and as last with mongoose create.

When I use forEach in mongoose I get a "Cannot set headers after they are sent to the client". I am aware that the forEach is not completely executed because a res.send has apparently already taken place. Otherwise it would at least not come to this error message.

How can I use mongoose with forEach so that the code only continues when the for forEach loop is complete?

Here my code:

Carts.find({ user: req.params.user }, function (err, product) {
if (err) {
return res.send({ isFound: false });
}
if (!product) {
return res.send({ isFound: false });
}
product.forEach(element => {
element.orderid = req.params.smaorderid
OrderD.create(element, function (err, orderitems) {
if (err) {
console.log(err)
return res.send({isCreated: false})
}
})
});
return res.send({isCreated: true})
})

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay