使用猫鼬将评论作为对象添加到帖子中的评论数组中,但是无法获取我在同一函数中发布回的评论

问题描述 投票:0回答:1

-我是新来的。请多多指教

  • 我尝试了各种猫鼬查找查询。

  • 这给出了未定义的错误

  • 如果我尝试

  • `const postedComment = postToComment.comments.find({commentId:uuid});,`
    
  • 这会给出状态 500 内部服务器错误。

      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: 
    

    发表评论}); } } 捕获(错误){ res.status(500).json(错误); } };

javascript node.js mongoose promise backend
1个回答
0
投票
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
      );
© www.soinside.com 2019 - 2024. All rights reserved.