所以我一直在製作一個類似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
});
});
});
});
我讀了貓鼬工作與稱爲填充的東西,但不是這只是插入帖子內的所有評論?我不想讓帖子文檔變成數據密集型...
有點失落..歡迎任何幫助,謝謝。
對不起,延遲到星期一纔回復。 這工作完美,我終於明白'ref'和'populate'意味着多虧你的例子。 爲了清楚起見,如果有人決定將這個例子用於他們自己的項目,我不得不改變'.populate('commentsIds')'comment ** s ** 除了這一切,一切工作都很直接。 謝謝:) –
太棒了,我在我的帖子中糾正了它,以避免任何混淆。 –