提问人:Phoenix Phoenix 提问时间:11/7/2023 最后编辑:Heretic MonkeyPhoenix Phoenix 更新时间:11/8/2023 访问量:47
用户正在关注自己
The user is following himself
问:
我编写了一个用于关注和取消关注用户的函数,在第一行代码中,我做了if语句,使用户不能关注自己,但用户可以关注自己,即使这样
以下用户代码:
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);
}
};
注意:我在路由器文件中使用post方法。这很好还是我应该为此使用(补丁或放置)?
答:
3赞
David
11/7/2023
#1
两个对象将不相同:
if(userToModify === currentUser) {
即使它们在直观上表示相同的信息,它们也是不同的对象实例。
但是看看你是如何获得这些对象的:
const userToModify = await User.findById(id);
const currentUser = await User.findById(req.user._id);
如果这些标识符相同,那么您正在获取同一记录的两个实例,对吗?然后只需比较标识符:
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);
0赞
Phoenix Phoenix
11/7/2023
#2
我通过在id后面添加方法解决了它,如下所示:toString()
if(id === req.user._id.toString())
等。
评论