【发布时间】:2014-05-17 00:41:19
【问题描述】:
考虑适合嵌套的博客/评论模式(即使您不同意):
var CommentSchema = new Schema({ name: String, body: String });
var BlogPostSchema = new Schema({ title: String, comments: [CommentSchema] });
我了解如何为博客文章添加、更新、删除 cmets,但所有这些方法都需要在父博客文章文档上调用 save() 方法:
blog_post.comments.push( new Comment({...}) );
blog_post.save();
我希望能够让 Comment 架构知道它嵌套在另一个架构中,这样我就可以在评论文档上调用 save() 并且它足够智能以更新父博客文章。在我的应用逻辑中,我已经知道博文 id,所以我想做这样的事情:
CommentSchema.virtual('blog_post_id');
CommentSchema.pre('save', function (next) {
var comment = this;
if( !comment.blog_post_id ) throw new Error('Need a blog post id');
BlogModel.findById( comment.blog_post_id, function(err, post) {
post.comments.push( comment );
post.save(next);
});
});
var comment = new Comment({ blog_post_id: 123, name: 'Joe', body: 'foo' });
comment.save();
上述方法可行,但我仍然会得到一个独立于博客文章的顶级评论集合(这正是 mongoose 的工作方式,我接受)。
问题:如何防止 Mongoose 创建单独的“评论”集合。在预保存方法中,我想调用next(),之后不进行任何写操作。有什么想法吗?
【问题讨论】:
标签: node.js mongodb mongoose middleware