【发布时间】:2013-09-29 03:22:33
【问题描述】:
我在 MongoDB 中有两个集合:一个保存博客的帖子数据,另一个保存具有以下模式的博客评论数据。如何使用 nodejs 和 mongoose 查询所有评论属于它的帖子并响应单页应用程序?谢谢!
var PostSchema = mongoose.Schema({
created: {
type: Date,
default: Date.now
},
content: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'user'
}
});
var CommentSchema = mongoose.Schema({
created: {
type: Date,
default: Date.now
},
content: {
type: String,
default: '',
trim: true
},
ofpost: {
type: Schema.ObjectId,
ref: 'post' //which post this comment belong to
},
user: {
type: Schema.ObjectId,
ref: 'user'
}
});
var Post = mongoose.model('Post', PostSchema);
var Comment = mongoose.model('Comment', CommentSchema);
//example:the Comment1 and Comment2 belong to Post1
var Post1 = new Post({ content: 'good day', user: 'John' });
var Comment1 = new Comment({content: 'yeah', ofpost: Post1._id, user:'Tom'})
var Comment2 = new Comment({content: 'agree', ofpost: Post1._id, user:'Tina'})
【问题讨论】:
-
你能解释一下
CommentSchema中的ref: 'post'吗? -
嗨@Amol M Kulkarni,我基于上述模式创建了两个模型,如下所示: var Post = mongoose.model('Post', PostSchema); var Comment = mongoose.model('Comment', CommentSchema);这是两个集合: var Post1 = new Post({ content: 'good day', user: 'John' }); var Comment1 = new Comment({content: 'yeah', ofpost: Post1._id, user:'Tom'}) var Comment2 = new Comment({content: 'agree', ofpost: Post1._id, user:'Tina' }) 所以 Comment1 和 Comment2 属于 Post1
-
根据您的 cmets
var Post1 = new Post({ content: 'good day', user: 'John' });没有_id字段;但是您将其用作参考,var Comment1 = new Comment({content: 'yeah', ofpost:Post1._id, user:'Tom'});。在您的架构中修复它,并在您的问题中更新。 -
我们保存后,mongodb会自动渲染_id。我已经做到了,而且有效。我的问题是我不知道如何将帖子和评论放在一起来回复客户。
-
您说“多对多”,但看起来每条评论都属于一个帖子——是这样吗?所以一个帖子可以有很多个cmet,但是一个评论只属于一个帖子。因此,“帖子到 cmets”的关系是“一对多”。对吗?
标签: node.js many-to-many schema mongoose single-page-application