2015-02-10 81 views
3

我試圖用另一個模型的數據填充模型。這兩個模型是這樣的:貓鼬查詢填充查找元素的匹配id

var postSchema = mongoose.Schema({ 
    _comments: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }, 
    type: String, 
    body: String, 
}); 

var commentSchema = mongoose.Schema({ 
    id_post: mongoose.Schema.Types.ObjectId, 
    body: String, 
}); 

我想找到所有postscommentsid_post == _id從創立帖子進行填充。這樣的事情:

Post.find({}).populate({ 
    path: '_comments', 
    select: 'body', 
    match: { post_id: Post._id } 
    options: { limit: 5 } 
}) 
.exec(function (err, posts){...}); 

回答

3

首先,你寫的代碼有幾個問題。 如果每一個帖子可以有很多意見,你應該實現你的架構之間的一個一對多的關係,你可以做到這一點通過周圍用[]

var postSchema = mongoose.Schema({ 
    _comments: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Comment'} ] , 
    type: String, 
    body: String, 
}); 

id_post不僅僅是一個類型的ObjectId現場評論裁判,應該這樣寫:

var commentSchema = mongoose.Schema({ 
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }, 
body: String, 
}); 

當保存一個新評論確保將其連接到其職位:

var comment = new Comment({ 
    body: "Hello", 
    post: post._id // assign the _id from the post 
    }); 

comment.save(function (err) { 
    if (err) return handleError(err); 
    // thats it! 
    }); 

現在,當你想找到一個後,填充它的意見,你應該寫這樣的事情:

Post 
.find(...) 
.populate({ 
    path: '_comments', 
    select: 'body', 
    options: { limit: 5 } 
}) 
.exec() 

我放棄比賽的原因是當您需要根據特定的字段來篩選匹配,應使用,你的情況,你可以用匹配只能獲得type ='something'的評論。

填充應該工作,因爲當你插入評論時,你使債券到其帖子。

使用填入的正確方法的更多信息可以在這裏找到 - Mongoose Query Population

後的數據應堅持以下方式:

{ 
    body: "some body", 
    type: "some type", 
    _comments: [12346789, 234567890, ...] 
} 

關於裁判會在這裏堅持的方式的更多信息 - One-to-Many Relationships with Document References

+0

'postSchema'中的'_comments'應該包含類似'[{_id:Comment.id}]''的東西。或'[{id_post:Post._id}]' – TGeorge 2015-02-10 20:14:47

+0

您可以在我的回答中找到修改後的postSchema,我剛剛以正確的方式添加了commentSchema以將其與Post相關聯。 – 2015-02-10 20:25:21

+0

在我的DATABASE裏,一個'post'文件是什麼樣的? '_comments'應該包含什麼? – TGeorge 2015-02-10 20:38:11