I am trying to set up conditional rendering using in the backend for allowing a user to update their profile. My first thought was to use a switch statement since it is a case by case on what they want to update (username, location, etc.), however I cannot get the validation to work case-by-case. Is there a more efficient way of doing this without using ReactJS? Below is the code and error log. I have removed the “break” clause in order for the switch to keep going in checking for an actual value. I have also tried “.trim().length” as part of the validation but the validation error i posted keeps popping as well.
profile.js
router.post("/update/:id", (req, res) => {
console.log("UPDATING ROUTE HIT n");
try {
console.log("MADE IT INSIDE THE TRY ROUTE n");
if (req.isAuthenticated()) {
User.findOne({ id: req.params.id }, (err, foundUser) => {
if (foundUser) {
console.log("FOUND USER n");
const newUpdate = {
username: req.body.username,
company: req.body.company,
location: req.body.location,
position: req.body.position,
};
switch (true) {
// THIS IS THE PROBLEM
case newUpdate.username !== "" && newUpdate.username !== User.find({ username: { $ne: null } }):
foundUser.username = newUpdate["username"];
case newUpdate.company !== "" && newUpdate.company.length >= 3:
foundUser.company = newUpdate["company"];
case newUpdate.location !== "" && newUpdate.location.length >= 3:
foundUser.location = newUpdate["location"];
case newUpdate.position !== "" && newUpdate.position.length >= 3:
foundUser.position = newUpdate["position"];
break;
default:
console.log("FAILED TO ENTER ANYTHING" + err + "n");
break;
}
foundUser.save((err) => {
if (err) {
console.log("THERE WAS AN ERROR: " + err + "n");
} else {
console.log("SUCCESSFULLY CHANGED POSITION");
}
});
res.redirect("/profile");
} else {
console.log("FOUND THE ANSWER" + err + "n");
}
});
}
} catch (error) {
console.log("THERE WAS AN ERROR(caught): " + error + "n");
}
});