我的删除路线是
const id = req.body.id;
const postId = req.body.postId;
if (mongoose.Types.ObjectId.isValid(id)) {
Comment.findByIdAndRemove({ _id: id }, (err, cRes) => {
if (err) return err;
Post.findOneAndUpdate({ _id: postId }, {
$pull: {
Comments: {
_id: id
}
}
}, (err, doc, res) => {
if (err) console.log(err);
res.redirect(req.get('referer'));
});
});
}
问题在于它确实删除了Comment
表中的评论,但它没有删除对相关Post
的评论,为什么会这样?
PostSchema
var PostSchema = new mongoose.Schema({
Author: String,
Title: String,
Description: String,
Comments: [{
type: mongoose.Schema.Types.ObjectId, ref: 'Comment'
}],
Tags: [{
type: mongoose.Schema.Types.String, ref: 'Tag'
}],
CreatedOn: Date,
LastEditOn: Date
});
CommentSchema
var CommentSchema = new mongoose.Schema({
_postId: {
type: String,
ref: 'Post'
},
Author: String,
Description: String,
CreatedOn: Date,
LastEditBy: Date
});
答案 0 :(得分:2)
无需在_id
期间提出pull
因为您未在Comments
Post
集合中提及任何密钥。
if (mongoose.Types.ObjectId.isValid(id)) {
Comment.findByIdAndRemove({ _id: id }, (err, cRes) => {
if (err) return err;
Post.update({ _id: postId }, {
$pull: {
Comments: id
}
}, (err, doc, res) => {
if (err) console.log(err);
res.redirect(req.get('referer'));
});
});
}
如果您在帖子架构中定义_id
,如
Comments: [{
_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }
}]
然后你的查询就可以了。