Reputation: 323
I have the following route using express and mongoose that update 2 collections from one route. The updates work and are reflected in MongoDb, however, at the end of the request the server crashes with the error: code: 'ERR_HTTP_HEADERS_SENT'. Is there a way for me to avoid this error?
router.post("/user-adopted", verify, (req, res) => {
const userId = req.body.userId;
const petId = req.body.petId;
User.findOneAndUpdate(
{ _id: userId },
{ adoptedPet: petId, petId: false, adoptionRequest: false },
function (err, result) {
if..else..
}
);
Data.findOneAndUpdate(
{ _id: petId },
{ adopted: true },
function (err, result) {
if...else..
);
});
Upvotes: 0
Views: 38
Reputation: 659
As soon as the User record is updated it performs the operation you have defined in the callback and Data record is left out so to prevent that do the updation of Data record in the callback of user and try to use updateOne() instead of findOneAndUpdate() :
User.updateOne(
{ _id: userId },
{ adoptedPet: petId, petId: false, adoptionRequest: false },
function (err, result) {
if(err) res.send(err)
Data.updateOne(
{ _id: petId },
{ adopted: true },
function (err, result) {
if(err)
res.send(err)
else{
// Redirect where you want to go
}
}
);
}
);
Upvotes: 1