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?
0 comments:
Post a Comment
Thanks