2015-02-06 93 views
1

所以我想弄清楚Mongo/Mongoose中的人口和關係。我有一個將會有很多預測的夾具。如果我想顯示預測的夾具,我可以簡單地使用填充方法,但是如果我需要顯示夾具的所有預測,該怎麼辦?MongoDB/Mongoose有很多關係

這聽起來很簡單,但也許我仍然有我的SQL頭試圖弄清楚。這很容易做還是以錯誤的方式接近它?這裏是我的模型 -

var FixtureSchema = new Schema({ 
homeTeam: { 
    type: Number, 
    required: true, 
    ref: 'Team' 
}, 
awayTeam: { 
    type: Number, 
    required: true, 
    ref: 'Team' 
}, 
date: { 
    type: Date 
}, 
matchday: { 
     type: Number, 
     required: true 
} 
}); 

var PredictionSchema = new Schema({ 
goalsHomeTeam: { 
    type: Number, 
    required: true 
}, 
goalsAwayTeam: { 
    type: Number, 
    required: true 
}, 
fixture: { 
    type: Number, 
    ref: 'Fixture' 
}, 
user: { 
    type: Schema.ObjectId, 
    ref: 'User' 
} 
}); 

回答

1

你必須先找到你想要的夾具,然後通過你的預測搜索和查找匹配。 Mongo沒有「反向」人口,但編寫你自己的很容易:

Prediction.find({fixture: fixture._id}, function(err, predictions) { 
    //do things with predictions 
}) 
+0

謝謝格蘭特。我的問題是如果我想要檢索一系列燈具並填充所有這些燈具的預測結果?那可能嗎? – 2015-02-07 16:11:15

+0

實際上並沒有一種簡單快捷的方法。你不能「填充」,因爲夾具不存儲所有預測的參考。您可以填充_id的數組,但是這會要求您在每次創建新預測時更新夾具對象。 另一個可能的解決方案是[異步庫](https://github.com/caolan/async)。具體來說就是「每個」功能。循環固定裝置,併爲每一個找到所有的預測並返回數組。 – 2015-02-08 22:19:30

+0

好極了。我相信這將解決我的問題。感謝您的幫助Grant。 – 2015-02-09 10:56:38