Node.js Mongoose使用post删除所有引用的评论
这是我的帖子模式。其中包含引用注释的集合Node.js Mongoose使用post删除所有引用的评论,node.js,mongoose,Node.js,Mongoose,这是我的帖子模式。其中包含引用注释的集合 const postSchema = new mongoose.Schema({ title: String, content: String, comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "Comment" }] }); const Post = mongoose.model("Post", postSchema); 这
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=wait Post.findByIdAndDelete(req.params.id);
wait Comment.deletemanny({u id:{$in:deleted.comments}});