I have a mongodb with express and I'm getting Cannot set headers after they are sent to the client. Unhandled promise rejections are deprecated error when doing the following.
exports.deleteBooking = (req, res, next) => {
req.body.courts.forEach(element => {
Booking.deleteOne({$and: [
{ cid: element.cid },
{ year: element.day.year }
]})
.then(result => {
res.status(201).json({
message: result
});
})
.catch(() => {
res.status(500).json({
error: 'error'
})
});
})
};
I am sending an array of objects to my server and want to perform one deletion per object.
Because of the forEach it might run the .catch after the headers are sent to the client. What is the correct way of handling .then and .catch with a forEach loop?
Thank you!
EDIT: I forgot to add that if I would delete the .then and .catch the query would still run, and without errors. But I would like to keep the error handling in this case.
Cannot read property 'then' of undefined