繁体   English   中英

如何使用 mongoose 和 nodejs 删除嵌套在 Post 模式中的评论?

[英]How to delete comment that is nested in Post schema with mongoose and nodejs?

我希望能够删除帖子 model 中的评论。

这是我发布 model 的架构:

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
     }
   ]

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

首先我们通过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");
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM