I have this Mongoose/Express code that lets you update a document from the logged in user. I am getting an error: node:events:368 throw er; // Unhandled 'error' event ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This is my code.
router.post("/update/:id", checkAuth, (req, res) => {
// check if the snippet was created by the user who is logged in and update the snippet with the new data from the request body
Snippet.findOne({
_id: req.params.id,
userId: req.userData.userId,
})
.then((snippet) => {
if (!snippet) {
return res.status(400).json({
message: "You don't have a snippet with this ID",
});
}
if (req.body.title) {
console.log("if statement");
Snippet.findOne(
{
title: req.body.title,
userId: req.userData.userId,
},
(titleCheckErr, titleCheckSnippet) => {
if (titleCheckErr) {
return res.status(500).json({
error: titleCheckErr,
});
}
if (titleCheckSnippet) {
return res.status(400).json({
message:
"You already have a snippet with that title",
});
}
}
);
snippet.title = req.body.title;
}
snippet.description = req.body.description;
snippet.code = req.body.code;
snippet.language = req.body.language;
// save the snippet
snippet.save((saveSnippetErr, saveSnippet) => {
if (saveSnippetErr) {
return res.status(500).json({
error: saveSnippetErr,
});
}
return res.status(201).json({
message: "Snippet updated",
snippet: saveSnippet,
});
});
})
.catch((err) => {
return res.status(500).json({
error: err,
});
});
});
I figured it out. I was making it too complicated. I simply changed it from using mongoose to check if the title exists, and made it a simple if statement that kept the title the same from db if there was no request body title. Here's the code.
router.post("/update/:id", checkAuth, (req, res) => {
// check if snippet was created by the user who is logged in, and update the snippet with new data from the request body
Snippet.findOne(
{ _id: req.params.id, userId: req.userData.userId },
(err, snippet) => {
if (err) {
return res.status(500).json({
error: err,
});
}
if (!snippet) {
return res.status(400).json({
message: "Snippet not found",
});
}
if (req.body.title) {
snippet.title = req.body.title;
} else {
snippet.title = snippet.title;
}
snippet.description = req.body.description;
snippet.code = req.body.code;
snippet.language = req.body.language;
// save the snippet
snippet.save((saveErr, saveSnippet) => {
if (saveErr) {
return res.status(500).json({
error: saveErr,
});
}
console.log("updated");
return res.status(201).json({
message: "Snippet updated",
snippet: saveSnippet,
});
});
}
);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.