删除某个博客文章的评论

时间:2019-04-11 20:48:30

标签: node.js angular mongodb express mongoose

我正在尝试删除某个博客帖子中即将被猫鼬删除的所有评论。我不太了解为什么我的代码无法正常工作。

const commentSchema = new mongoose.Schema({
  message: { type: String, required: true },
  likes: { type: Number, default: 0 },
  parentBlog: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "Blog"
  },
  commenter: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "User"
  }
});

router.delete("/:title_url", checkAuth, (req, res) => {
  const successMessage = "Successfully deleted blog post.";
  const errorMessage = "Error in deleting blog post.";
  Blog.findOne({ title_url: req.params.title_url })
    .then(foundBlog => {
      Comment.deleteMany({
        parentBlog: foundBlog._id
      });
      foundBlog.remove();
      console.log(foundBlog);
      return res.status(200).json({ message: successMessage });
    })
    .catch(res.status(500).json({ message: errorMessage }));
});

console.log已正确记录,就在我收到以下错误之前:

(node:3108) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

编辑:这是我最后的可行解决方案。

// delete Blog Post route
router.delete("/:title_url", checkAuth, (req, res) => {
  const successMessage = "Successfully deleted blog post.";
  const errorMessage = "Error in deleting blog post.";
  // delete Post
  Blog.findOneAndRemove({ title_url: req.params.title_url })
    .populate("comments")
    .then(async foundBlog => {
      // delete Comment references from Commenters
      await foundBlog.comments.forEach(async comment => {
        await User.findByIdAndUpdate(comment.commenter._id, {
          $pull: { comments: comment._id }
        });
      });
      // delete Post reference from Post Author
      await User.findByIdAndUpdate(foundBlog.author, {
        $pull: { blogs: foundBlog._id }
      });
      // delete all child Comments
      await Comment.deleteMany({
        parentBlog: foundBlog._id
      });
      return res.status(200).json({ message: successMessage });
    })
    .catch(() => res.status(500).json({ message: errorMessage }));
});

1 个答案:

答案 0 :(得分:0)

您可以尝试-

router.delete("/:title_url", checkAuth, async (req, res) => {
    const successMessage = "Successfully deleted blog post.";
    const errorMessage = "Error in deleting blog post.";
    try {
        let foundBlog = await Blog.findOne({ title_url: req.params.title_url });
        Comment.deleteMany({
            parentBlog: foundBlog._id
        });
        foundBlog.remove();
        console.log(foundBlog);
        res.status(200).json({ message: successMessage });
    } catch (error) {
        res.status(500).json({ message: errorMessage })
    }
});

实际上,您不是在处理诺言拒绝。 我认为这种方式使代码更清晰易读 希望对您有所帮助。