skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. In your code, replace post.likes with post.reactions[req.params.reactionType], add param validation (and empty array creation when it does not exist) and you’re good to go.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search