首页 > 解决方案 > 如何使用 mongoose 和 nodejs 删除嵌套在 Post 模式中的评论?

问题描述

我希望能够删除我的 Post 模型中的评论。

这是我的 Post 模型架构:

const PostSchema = new Schema({
    userID: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    },
    content: {
        type: String,
        required: true
    },
    registration_date: {
        type: Date,
        default: Date.now
    },
    likes: [
        {
            type: Schema.Types.ObjectId,
            ref: "user"
        }
    ],
    comments: [
        {
            text: String,
            userID: {
                type: Schema.Types.ObjectId,
                ref: 'user'
            }
        }
    ]
})

我有这条路线:

router.delete('/comment/:id/:comment_id', auth, async (req, res) => {
    const postId = req.params.id
    const commentId = req.params.comment_id
}

帖子中的评论如下所示:

 comments: [
     {
       _id: 5f1df4cf5fd7d83ec0a8afd8,
       text: 'comment 1',
       userID: 5efb2296ca33ba3d981398ff
     },
     {
       _id: 5f1df4d35fd7d83ec0a8afd9,
       text: 'commnet 2',
       userID: 5efb2296ca33ba3d981398ff
     }
   ]

我想删除评论,不知道怎么做。有谁知道该怎么做?

标签: node.jsexpressmongoosemern

解决方案


首先我们找到帖子,然后我们从评论数组中findByIdAndUpdate删除评论。$pull

router.delete("/comment/:id/:comment_/id", async function (req, res) {
  try {
    const post = await Post.findByIdAndUpdate(
      req.params.id,
      {
        $pull: { comments: {_id:req.params.comment_id}},
      },
      { new: true }
    );

    if (!post) {
      return res.status(400).send("Post not found");
    }
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

推荐阅读