2016-09-30 69 views
0

所以我一直在制作一个类似Instagram的web应用程序。 用户可以发表帖子(图片+说明),其他用户可以对图片发表评论。显示ExpressJs和Mongoose每个帖子的所有评论

每篇文章都包含一个注释ID数组。 每条评论都包含对其帖子的引用。

我无法弄清楚的是如何查询(查找所有帖子,为每个帖子获取评论 - >渲染视图)。

这里的架构是什么样子

//## models/post.js 
var Post = new Schema({ 
    author  : {type: String, required: true}, 
    desc  : {type: String}, 
    imageUrl : {type: String}, 
    commentsIds: [{type:Schema.ObjectId, ref:'Comment'}], 
    likes  : {type: Number, default: 0}, 
    created_at : {type:Date, default: Date.now} 
}); 

//## models/comment.js 
var Comment = new Schema({ 
    username : {type: String, required: true}, 
    content : {type: String, required: true}, 
    post  : {type:Schema.ObjectId, ref:'Post'}, 
    created_at: Date 
}); 

和我的路由器是这样的时刻“作品”,如没有错误,但它是所有posts..not下输出所有评论只是他们各自的职位就像我想要的。

// routes.js 
router.get('/', function(req, res) { 
    Post.find(function(err, posts, count){ 
    Comment.find({post: {$in: posts}}, function (err, comments, count){ 
     res.render('index', { 
     user: req.user, 
     page : 'index', 
     title : 'トップページ', 
     posts : posts, 
     comments : comments 
     }); 
    }); 
    }); 
}); 

我读了猫鼬工作与称为填充的东西,但不是这只是插入帖子内的所有评论?我不想让帖子文档变成数据密集型...

有点失落..欢迎任何帮助,谢谢。

回答

1

根据您的模式,您已经将每个注释包含在引用中......最好不要在模式中包含无限数组作为良好实践的一个问题,尤其是因为您已在注释中引用到父职位。

但是既然你已经有了注释的阵列安置自己的模式,你可以简单地做以下包括数据中的每个评论的全部细节,从您的查询返回:

router.get('/', function(req, res) { 
    Post.find({}) 
    .populate('commentsIds') 
    .exec(function(err, posts, count){ 
     res.render('index', { 
     user: req.user, 
     page : 'index', 
     title : '??????', 
     posts : posts 
     }); 
    }); 
}); 

填充没有按” t将任何额外的东西存储在您尚未存储的MongoDB中,您当前在每个帖子中存储了一个commentIds数组,填充后只需将所有这些注释替换为commentIds数组以显示结果。

+0

对不起,延迟到星期一才回复。 这工作完美,我终于明白'ref'和'populate'意味着多亏你的例子。 为了清楚起见,如果有人决定将这个例子用于他们自己的项目,我不得不改变'.populate('commentsIds')'comment ** s ** 除了这一切,一切工作都很直接。 谢谢:) –

+0

太棒了,我在我的帖子中纠正了它,以避免任何混淆。 –

相关问题