I have created a route for people to like posts on my current project and this is the code that I have so far:
router.post("/like", (req, res) => {
const userLiking = req.body.userLiking;
const postid = req.body.postid;
db.query(
"INSERT INTO likes (userLiking, postid) VALUES(?,?)", [userLiking, postid], (err, results) => {
if (err) {
console.log(err);
}
db.query("UPDATE post SET likes = likes + 1 WHERE id = ?", postid, (err2, results2)=> {
res.send(results);
})
}
);
I would like to add a condition where it checks in my sql database first whether the user has already liked the post in question, for example
“NOT EXISTS ( SELECT 1 FROM likes WHERE userLiking= userLiking AND postid= postid)”
Idealy it would detect if a row already exists where the userLiking and postid are already there, if it’s the case delete it, thus removing the like, however, I don’t know how to incorporate such a condition in my route… All help is much appreciated, thanks!