'Mongoose add an object to nested array of objects in the database using push method
in this function i find the post by post id then find a specific comment within this post by comment id, then i check if the nested array of objects likes contains user id, if no then i push user id to likes array, otherwise i remove it, but it doesn't work as it doesn't add the user id to likes array, what's wrong?
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);
}
};
Solution 1:[1]
the answer is i need to do post.save();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aasem shoshari |
