【发布时间】:2017-02-08 12:39:25
【问题描述】:
所以我一直在制作一个“类似 instagram”的网络应用程序。 用户可以发帖(图片+描述),其他用户可以评论图片。
每个帖子都包含一组评论 ID。 每条评论都包含对其帖子的引用。
我不知道如何查询(查找所有帖子,为每个帖子获取 cmets -> 渲染视图)。
这是架构的样子
//## 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
});
我的路由器目前是这样“工作”的,因为没有错误,但它正在输出所有帖子下的所有 cmets..而不仅仅是我想要的他们各自的帖子。
// 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
});
});
});
});
我读过 mongoose 使用名为 populate 的东西工作,但这不只是将所有 cmets 插入帖子中吗?我不希望发布文档成为数据密集型...
有点失落..欢迎任何帮助,谢谢。
【问题讨论】: