【问题标题】:How to delete comment that is nested in Post schema with mongoose and nodejs?如何使用 mongoose 和 nodejs 删除嵌套在 Post 模式中的评论?
【发布时间】:2020-11-16 05:57:37
【问题描述】:

我希望能够删除 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
}

帖子中的cmets如下所示:

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

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

【问题讨论】:

    标签: node.js express mongoose mern


    【解决方案1】:

    首先我们找到 findByIdAndUpdate 的帖子,然后我们从 cmets 数组中删除使用 $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");
      }
    });
    

    【讨论】:

    • 什么都没有被删除,我用同样的 cmets 得到同样的帖子
    • 我修复了这个问题,它应该是:`$pull: { cmets: {_id: req.params.comment_id} }`,谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 2021-09-09
    • 2012-09-17
    • 2020-07-18
    • 2016-11-18
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多