2014-04-27 352 views
0

因此,這裏是我的模型:填充嵌套ObjectRef

CompetitionSchema = new Mongoose.Schema 
name : 
    type : String 
    required : true 
required_teams : 
    type : Number 
teams : [ 
    _team : 
    type : Mongoose.Schema.ObjectId 
    ref : 'teams' 
    weight : 
    type : Number 
    min : 0 
] 

我希望能夠填充競爭對象,以便訪問competition.teams[0]._team._id爲此我曾嘗試以下:

models('Competition') 
    .findById id 
    .populate('teams._team') 
    .exec (error, competition) -> 
    if error || !competition 
     error_callback error 
    else 
     success_callback competition 

但是這沒有效果。我也試過:

models('Competition') 
    .findById id 
    .exec (error, competition) -> 
    if error || !competition 
     error_callback error 
    else 
     options = [ 
     path : 'teams._team' 
     model : 'teams' 
     ] 
     models('Competition') 
     .populate(
     competition 
     , options 
     , (error, competition) -> 
      if error || !competition 
      error_callback competition 
     else 
      success_callback competition 
    ) 

也沒有效果。我發現API documentation for Model.populate是相當混亂的,所以請原諒,如果它是明顯的明顯!

回答

0

OK多一點,我終於來到了主題中浸泡自己後,下面的:

models('Competition') 
    .findById id 
    .exec (error, competition) -> 
    if error || !competition 
     error_callback error 
    else 
     options = [ 
     path : '_team' 
     model : 'teams' 
     ] 
     models('Team') 
     .populate(
     competition.teams 
     , '_team' 
     , (error, competition_teams) -> 
      if error || !competition_teams 
      error_callback competition 
     else 
      success_callback competition 
    ) 

它歸結爲:與其說

Competition.populate(competition, { path : 'teams._team' } , callback); 

我現在呼籲的:

Team.populate(competition.teams, '_team', callback); 

這有益於修改competition.teams數組而不是返回副本,所以原來的competition對象也收到改變!