hello please any one can help me I need route for multiple reactions.
this code is for one like but I need for many for example (like, love, heat,….)
something like Facebook reactions
and thank you.
CODE:
exports.likeAndUnlikePost = async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({
success: false,
message: "Post not found",
});
}
if (post.likes.includes(req.user._id)) {
const index = post.likes.indexOf(req.user._id);
post.likes.splice(index, 1);
await post.save();
return res.status(200).json({
success: true,
message: "Post Unliked",
});
} else {
post.likes.push(req.user._id);
await post.save();
return res.status(200).json({
success: true,
message: "Post Liked",
});
}
} catch (error) {
res.status(500).json({
success: false,
message: error.message,
});
}
};
2
Answers
Are you using express ?
I think you can create an array of reactions with id, then based on received reaction id you can create a reaction
In your code, replace
post.likes
withpost.reactions[req.params.reactionType]
, add param validation (and empty array creation when it does not exist) and you’re good to go.