Reputation: 143
When I try to handle errors in mongoose.findOne()
function, I wanted to use second parameter like this mongoose.findOne({ uuid: uuid }, (err,doc))
but can not see any error because of the following error :
throw er; // Unhandled 'error' event
await endPointSchema.findOne({ uuid: uuid }, (err, doc) => {
if (err) {
res.status(403).json({ message: "Something went wrong!" });
return;
}
if (!doc.endpoint) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
data.save();
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
}
doc.endpoint = [...doc.endpoint, {Endpoint: Content}]
doc.save()
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return
});
(node:8140) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (C:\Users\admin\Desktop\Nedim Akar\project-a server\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\admin\Desktop\Nedim Akar\project-a server\node_modules\express\lib\response.js:170:12)
route.post("/endpoint", AuthorizePanel, async (req, res) => {
const { role, username, uuid } = req.user;
if (!role && !username && !uuid) {
res.sendStatus(401);
return;
}
const { Endpoint, Content } = req.body;
if (Endpoint === username) {
res.status(403).json({ message: "Endpoint can not be same with your username!" });
return;
}
try {
const doc = await endPointSchema.findOne({ uuid: uuid })
if (!doc.endpoint) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
}
doc.endpoint = [...doc.endpoint, {Endpoint: Content}]
await doc.save()
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return
} catch(e) {
res.status(403).json({ message: "Something went wrong!" });
}
});
What I use ?
^4.17.1
^5.12.14
Upvotes: 1
Views: 172
Reputation: 8773
You should not use async/await and callbacks at the same time. This is how you should refactor the code :
try {
const doc = await endPointSchema.findOne({ uuid: uuid })
if (!doc.endpoint) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
}
doc.endpoint = [...doc.endpoint, {Endpoint: Content}]
await doc.save()
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return
} catch(e) {
res.status(403).json({ message: "Something went wrong!" });
}
Upvotes: 1