Mongoose使用push方法将一个对象添加到数据库中的嵌套对象数组中



在这个函数中,我通过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();

最新更新