2016-09-30 76 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

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

相關問題