我是NodeJS和Mongo的新手,我想知道是否有人可以帮我解决这个问题。我想删除一个博客文章的架构,其中包含一个引用“注释”架构的数组。
以下是模型:
var blogSchema = new Schema({
title: String,
author: String,
body: String,
likes: { type: Number, default: 0 },
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
date: { type: Date, default: Date.now }
});
var commentSchema = new Schema({
body: String,
author: String,
post: {type: Schema.Types.ObjectId, ref: 'Post'}
});
这就是我发现我的博文的方式:
router.param('post', function(req, res, next, id){
var query = Blog.findById(id);
query.exec(function (err, blogPost){
if(err){
return next(err);
}
if(!blogPost){
return next(new Error("Can't find post"));
}
req.blogPost = blogPost;
return next();
});
});
以下是我想弄清楚的代码:
router.delete('/posts/:post/remove', function(req, res, next){
var postToRemove = req.blogPost;
postToRemove.remove(function(req, res, next){
//... what should I do in here?
}
}
谢谢你帮助大家!
答案 0 :(得分:0)
假设帖子查询参数是要删除的帖子的标题,您可以尝试以下 syntax :
router.delete('/posts/:post/remove', function(req, res, next){
var postToRemove = req.params.post;
Blog.remove({title: postToRemove}, function(req, res, next){
if (err) return next(err);
res.json(post);
}
}
或者,您可以使用 findOneAndRemove()
方法:
router.delete('/posts/:post/remove', function(req, res, next){
var postToRemove = req.params.post;
Blog.findOneAndRemove({title: postToRemove}, function(req, res, next){
if (err) return next(err);
res.json(post);
}
}
或者如果您事先知道了ID,则可以使用 findByIdAndRemove()
方法,如下所示:
router.delete('/posts/:id/remove', function(req, res, next){
Blog.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
}