Search code examples
javascriptnode.jsmongoosepromisebackend

Added a comment as an object to a comments array in a post using mongoose,but, UNABLE to get that comment i posted back in the same function


I am new here. Kindly advice

  • I tried various mongoose find queries.
  • This gives undefined as error
  • If i try
const postedComment = postToComment.comments.find({commentId:uuid});
  • This is giving status 500 internal server error.
export const commentOnPost = async (req, res) => {
          const uuid = uuidv4();
          try {
            const postToComment = await Post.findById(req.params.postId);
            if (!postToComment) {
              res.status(400).json({ error: "Post not found" });
            } else {
               console.log(req.body, "body check ");
               const commentObject = {
                userId: req.userId,
                comment: req.body.comment,
                commentId: uuid,
              };
               await postToComment.updateOne({
                 $push: { comments: commentObject },
              });
              const postedComment = postToComment.comments.find(
                 (comment) => comment.commentId === uuid
              );
               console.log(postedComment,"comment that was posted");
    
              res
                .status(200)
            .json({ message: "Commented successfully", comment: 
    postedComment });
            }
           } catch (err) {
             res.status(500).json(err);
         }
};

Solution

  • The problem is solved by getting the post data once again and then performing the find() on that post.

    const postToComment2 = await Post.findById(req.params.postId);
       const postedComment = postToComment2.comments.find(
        (comment) => comment.commentId === uuid
    );