I am using the Model.findOne
method from mongoose to find and add some new data into a document. What kind of data is added is based on conditional if
statements. See below:
companyTotal.findOne({companyName: "xyz"}, function (err, doc) {
if (err) {
sendJsonResponse(res, 400, err)
} else if (doc) {
if (req.body.q1 === "poor") {
doc.poor += 1;
} else if (req.body.q1 === "okay") {
doc.okay += 1;
} else if (req.body.q1 === "well") {
doc.well += 1;
} else if (req.body.q1 === "very well") {
doc.veryWell += 1;
} else {
sendJsonResponse(res, 401, {"message": "Wrong data entry."})
}
}
doc.save(function (err, data) {
if (err) {
sendJsonResponse(res, 400, err)
} else {
sendJsonResponse(res, 200, data);
}
});
});
If none of the conditional statements are met I want to end the request and send an error message back. I am using the sendJsonResponse
function to handle any kind responses that need to be sent to the user along with the status codes.
function sendJsonResponse(res, status, content) {
res.status(status);
res.json(content);
}
Based on my knowledge res.json
calls res.end();
which then ends the request. But everytime the condition is not met it displays the error message BUT still runs the doc.save()
method and adds the data into the document.
What am I doing wrong? How can I end a request within if
statements if conditions are not met?