我遵循Thinkster的MEAN堆栈教程(https://thinkster.io/tutorials/mean-stack),该教程没有说明应该如何实现删除操作。MongoDB:如何删除已删除帖子的所有评论?
目前,我有以下模式:
var PostSchema = new mongoose.Schema({
title: {type: String, required: true, maxlength: 140},
link: {type: String, required: true, maxlength: 300},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
var CommentSchema = new mongoose.Schema({
body: {type: String, maxlength: 200, minlength: 1},
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
});
我有一个角工厂CRUD操作。我目前删帖有以下工厂方法:
o.deletePost = function(id) {
return $http.delete('/posts/' + id, null, {}
}).success(function(res){
$window.location.href = '/#/home';
return res.data;
});
};
我的路由器删除这个样子的:
// DELETE a post
router.delete('/posts/:post', function(req, res, next) {
Post.remove({_id: req.params.post}, function(err, post) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
不幸的是,当我删除这样的任何相关意见的地方留在后数据库。所以,我的问题是如何删除与帖子相关的所有评论,同时删除该帖子?
我试过Google的答案,它似乎我应该以某种方式使用MongoDB的中间件。我试过了:
// Remove Post
module.exports.removePost = function(id, callback){
Post.findById(id, function (err, doc) {
if (err) {}
doc.remove(callback);
})
}
//Remove comments related to post
PostSchema.pre('remove', function(next) {
this.model('Comment').remove({ post: this._id }, next);
});
但是这并没有做任何事情,因为我不知道如何从我的CRUD工厂调用它。即使我做了也不知道它是否正确。所以,任何帮助将受到欢迎。 :)
你甚至没有得到'成功删除'的消息吗?你有没有试过用[Postman](https://www.getpostman.com/)进行测试? – gh0st
@ gh0st我用路由器信息更新了我的问题。 – catfood
@ gh0st我收到邮件,我可以删除没有问题的帖子。问题是,当我删除一篇文章时,所有相关的评论都留在数据库中“浮动”。我想删除关联的帖子时删除它们。 – catfood