在这个函数中,我通过post id
找到post
,然后通过comment id
在这个帖子中找到一个特定的comment
,然后我检查对象的嵌套数组likes
是否包含user id
,如果没有,则我将user id
推到likes
数组,否则我将其删除,但它不起作用,因为它没有将user id
添加到likes
数组,怎么了?
const likeComment = async (req, res) => {
try {
const post = await Post.findById(req.body.postId);
const comment = post.comments.find(
(comment) => comment.id === req.body.commentId
);
if (comment.likes.includes(req.body.userId)) {
var index = comment.likes.indexOf(req.body.userId);
if (index !== -1) {
comment.likes.splice(index, 1);
}
res.status(200).json("you disliked this comment");
} else {
comment.likes.push(req.body.userId);
res.status(200).json("you liked this comment");
}
} catch (err) {
console.log(err);
res.status(500).json(err);
}
};
答案是我需要做post.save();