skip to Main Content

I wrote a function for following & unfollowing users and in the first line of code I made if statement to make it so the user can’t follow himself but the user can follow himself even though that

the followUser code:

const followUnfollowUser = async(req, res) => {
    try {
        const { id } = req.params;
        const userToModify = await User.findById(id);
        const currentUser = await User.findById(req.user._id);

        if(userToModify === currentUser) {
            return res.status(400).json({ message: "You cannot follow/unfollow yourself!" });
        }

        if(!userToModify || !currentUser) return res.status(400).json({ message: "User not found!" });

        const isFollowing = currentUser.following.includes(id);

        if (isFollowing) {
            // unfollow user
            await User.findByIdAndUpdate(id, { $pull: { followers: req.user._id } });
            await User.findByIdAndUpdate(req.user._id, { $pull: { following: id } });
            res.status(200).json({ message: "User unfollowed successfully" });
        } else {
            // Follow User
            await User.findByIdAndUpdate(id, { $push: { followers: req.user._id } });
            await User.findByIdAndUpdate(req.user._id, { $push: { following: id } });
            res.status(200).json({ message: "User followed successfully" });
        }
    } catch (err) {
        res.status(500).json({ message: err.message });
        console.log("Error in follow or unfollow User: ", err.message);
    }
};

Note: I’m using post method in router file. Is this fine or I should use (patch or put) for that?

2

Answers


  1. Chosen as BEST ANSWER

    I solved it by adding toString() method after the id like this:

    if(id === req.user._id.toString()) etc.


  2. Two objects will not be the same:

    if(userToModify === currentUser) {
    

    Even if they intuitively represent the same information, they are different object instances.

    But look at how you get those objects:

    const userToModify = await User.findById(id);
    const currentUser = await User.findById(req.user._id);
    

    If those identifiers are the same then you’re fetching two instances of the same record, right? Then just compare the identifiers:

    const { id } = req.params;
    
    if(id === req.user._id) {
        return res.status(400).json({ message: "You cannot follow/unfollow yourself!" });
    }
    
    const userToModify = await User.findById(id);
    const currentUser = await User.findById(req.user._id);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search