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)