猫鼬删除所有带帖子的引用评论

编程入门 行业动态 更新时间:2024-10-09 05:16:54

猫鼬删除所有带<a href=https://www.elefans.com/category/jswz/34/1771304.html style=帖子的引用评论"/>

猫鼬删除所有带帖子的引用评论

这是我的帖子架构。其中包含参考注释的集合。

const postSchema = new mongoose.Schema({
    title: String,
    content: String,
    comments: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
    }]
});
const Post = mongoose.model("Post", postSchema);

这是我的评论架构。

const commentSchema = new mongoose.Schema({
    text: String
});
const Comment = mongoose.model("Comment", commentSchema);

这是我删除帖子的代码。

Post.findByIdAndDelete(req.params.id, err => {
    if (!err) {
        res.redirect("/posts");
    } else {
        console.log(err);
        res.redirect("back");
    }
});

现在,我想删除所有引用此帖子的评论。现在我该怎么办。

回答如下:

这里我将deleteMany$in运算符一起使用。

const deleted = await Post.findByIdAndDelete(req.params.id);

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

更多推荐

猫鼬删除所有带帖子的引用评论

本文发布于:2024-05-13 09:52:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759395.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:帖子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!