Node + Express Mongoose子集合文档插入

我有一个Node + Express项目正在运行,我正在构build一个基本的博客系统,具有以下模式和模式

var Post = mongoose.Schema({ title: String, body: String, author: String, dateCreated: {type: Date, default: Date.now }, comments: [{author: String, body: String, date: Date}] }); var Post = db.model('Post', Post); 

我通过以下代码接受发布请求,并从中更新标题,正文和作者

 app.post('/addpost', function(req,res){ console.log(req.body.post); var post = new Post(req.body.post); post.save(function(err){ if(!err){ res.redirect('/'); }else{ res.redirect('/'); } }) }) 

我有的问题是,如何使用我已经开发的结尾添加注释到模式?

req.body.post输出

 { title: 'Hello World', body: 'This is a body', author: 'Bioshox' } 

这对于mongoose来说显然是可以接受的,但为了补充意见,我该如何去做呢?

谢谢!!

你可以使用下面的代码片段:

 var comment = { author: req.body.post.author , body: req.body.post.body, date: new Date() }; Post.findOneAndUpdate( { title: req.body.post.title }, { $push: { comments: comment }}, { safe: true, upsert: true }, function(err, blogModels) { // Handle err }); 

这段代码只是试图find一个Blog文章,如果它成功,然后$push新评论,否则,添加一个博客文章与初步评论。 所以,你的最终代码应该是这样的:

 app.post('/addpost', function(req,res) { var comment = { author: req.body.post.author , body: req.body.post.body, date: new Date() }; Post.findOneAndUpdate( { title: req.body.post.title }, { $push: { comments: comment }}, { safe: true, upsert: true }, function(err, blogModels) { // Handle err }); });