exports.manageLike = (req, res, next) => { // grabs user id let userId = req.body.userId; // grabs sauce id let sauceId = req.params.id; // grabs 'like' in request body let like = req.body.like; if (like === 1) { // if user smashes the like button // => updates the sauce given its id Sauce.updateOne( { _id: sauceId }, { // [ mongoDB push operator ] // pushes userId to usersLiked: [array] $push: { usersLiked: userId }, // [ mongoDB increment operator ] // increments likes [array] $inc: { likes: +1 }, } ) .then(() => res.status(200).json({ message: "Like ajouté par l'utilisateur !" }) ) .catch((error) => res.status(400).json({ error })); } if (like === -1) { // if user smashes the dislike button // => updates the sauce given its id Sauce.updateOne( { _id: sauceId }, { // [ mongoDB push operator ] // pushes userId to usersDisliked: [array] $push: { usersDisliked: userId }, // [ mongoDB increment operator ] // increments dislikes [array] $inc: { dislikes: +1 }, } ) .then(() => res.status(200).json({ message: "Dislike ajouté par l'utilisateur !" }) ) .catch((error) => res.status(400).json({ error })); } // Remove like / dislike if (like === 0) { Sauce.findOne({ _id: sauceId, }) .then((sauce) => { // remove like // if user has already liked if (sauce.usersLiked.includes(userId)) { Sauce.updateOne( { _id: sauceId }, { $pull: { usersLiked: userId }, $inc: { likes: -1 } } ) .then(() => res .status(200) .json({ message: "Like retiré par l'utilisateur !" }) ) .catch((error) => res.status(400).json({ error })); } // remove dislike // if user has already disliked if (sauce.usersDisliked.includes(userId)) { Sauce.updateOne( { _id: sauceId }, { $pull: { usersDisliked: userId }, $inc: { dislikes: -1 } } ) .then(() => res .status(200) .json({ message: "Dislike retiré par l'utilisateur !" }) ) .catch((error) => res.status(400).json({ error })); } }) .catch((error) => res.status(400).json({ error })); } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter