Answer the question
In order to leave comments, you need to log in
Like / Unlike on the same route?
There is a route in the node project that likes / removes likes.
What best practice will be in this case?
Should I make a separate route ('/unlike/:id') to remove a like?
router.put("/like/:id", auth, async (req, res) => {
try {
const comment= await Comment.findById(req.params.id);
if (
comment.likes.filter(like => like.user.toString() === req.user.id).length > 0
) {
const removeIndex = comment.likes
.map(like => like.user.toString())
.indexOf(req.user.id);
comment.likes.splice(removeIndex, 1);
} else {
comment.likes.unshift({ user: req.user.id });
}
await comment.save();
res.json(comment.likes);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
Answer the question
In order to leave comments, you need to log in
Should I make a separate route ('/unlike/:id') to remove a like?
router.delete("/like/:id", auth, async (req, res) => {
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question