我在MongoDB中像這樣的造型兩種類型的事件(事件和子事件)的嵌入文檔:建模參考使用貓鼬
var EventSchema = mongoose.Schema({
'name' : String,
'subEvent' : [ SubeventSchema ]
});
var SubeventSchema = mongoose.Schema({
'name' : String
});
現在,當我查詢子事件我希望能夠還檢索數據關於其相應superevent,因此使用貓鼬種羣特徵可能看起來像這樣獲取的一些示例數據:
EventModel.findOne({
name : 'Festival'
})
.populate('subEvent')
.execute(function (err, evt) { return evt; });
{
name : 'Festival',
subEvent: [
{ name : 'First Concert' },
{ name : 'Second Concert' }
]
}
EventModel.findOne({
'subEvent.name' : 'FirstConcert'
}, {
'subEvent.$' : 1
})
.populate('superEvent') // This will not work, this is the actual problem of my question
.execute(function (err, subevt) { return subevt; });
{
name: 'First Concert',
superEvent: {
name: 'Festival'
}
}
一個解決方案,我能想到的是不嵌入,但引用這樣的:
var EventSchema = mongoose.Schema({
'name' : String,
'subEvent' : [ {
'type' : mongoose.Schema.Types.ObjectId,
'ref' : 'SubeventSchema'
} ]
});
var SubeventSchema = mongoose.Schema({
'name' : String,
'superEvent' : {
'type' : mongoose.Schema.Types.ObjectId,
'ref' : 'EventSchema'
}
});
雖然我正在尋找基於第一個使用嵌入子事件的示例的解決方案。這是否可以實現,如果是,如何?
感謝您的回覆!我已經閱讀了相應的文檔,您的解決方案實際上就是我在第二個示例中的含義。這會迫使我改變模式,這正是我的第一個例子。我會爲我的問題添加更多的細節。 – hielsnoppe 2014-09-10 12:11:39
@hielsnoppe如果你真的希望,你可以離開並改變。但你的問題仍然基本上是「如何限制填充下的相關模式返回的字段」。這基本上是答案,沒有什麼會改變這一點。所以如果你想在你的相關模式中有更多的字段,那麼你將不得不添加它們。沒有別的方法,除非你的模式不是「嚴格」 – 2014-09-10 12:16:42
所以你的意思是我將不得不添加一個'superEvent'字段到SubeventSchema引用子事件嵌入的事件?這似乎是多餘的,因爲協會應該通過嵌入來清楚,但如果沒有其他方式,我會這樣做。這也不能導致人口中的循環? – hielsnoppe 2014-09-10 12:27:13