如何在MongoDB中删除许多关系文档?

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

帖子收藏

 Post : 
    _id : 001,
    comments : [1,2,3] // ObjectId

评论集

 Comment: 
    { _id : 1, message : "Bar" },
    { _id : 2, message : "Foo" },
    { _id : 3, message : "Bazz" }

我想删除一个帖子以及对该帖子的所有评论。但是如何删除其所有注释?

更新


后模式
{
    model: String,
    stock: Number,
    images: [String],
    price: Number,
    views: { type: Number, default: 1 },
    commentsCount: { type: Number, default: 0 },
    comments: [{ type: Schema.Types.ObjectId, ref: "postComments" }],
    postedBy: { type: String, ref: "publisherInfo" }
  },

postComments模式

{
    sender: String,
    createAt: { type: Date, default: Date.now },
    votes: { type: Number, default: 0 },
    contain: String
  },
mongodb mongoose
2个回答
1
投票

您可以使用findByIdAndDelete将删除该文档并返回它。现在,我们可以动态创建一个注释id数组,并将其与deleteMany和$ in运算符一起使用。

router.delete("/posts/:id", async (req, res) => {
  try {
    const result = await Post.findByIdAndDelete(req.params.id);

    let commentIds = result.comments.map((c) => c._id);

    await Comment.deleteMany({
      _id: {
        $in: commentIds,
      },
    });

    res.send("OK");
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

0
投票

这样,您可以安全地查询并删除所有评论。如果您已经具有ObjectId(id)格式的ID,请删除[C0

ObjectId
© www.soinside.com 2019 - 2024. All rights reserved.