2014-10-02 90 views
0

我一直在試圖解決這個問題約4小時,現在我找不到解決方法。我有3種型號,看起來像這樣:填充貓鼬互聯模型

第一個1是我的比賽模式:

var tournamentSchema = mongoose.Schema({ 
tournamentName: String, 
nrOfPlayers: String, 
players: [{ 
    type: mongoose.Schema.Types.ObjectId, ref: "User" }], 
openForLeagues: { 
    "leagues" : [] 
}, 
organizer: [{ 
    type: mongoose.Schema.Types.ObjectId, ref: "User" 
}] 
}); 

:第二個是我的用戶模型:

var userSchema = mongoose.Schema({ 

local : { 
nickname: String, 
battlenetid: String, 
email: String, 
password: String, 
race: String, 
league: String, 
role: String, 
website: String, 
avatarImage: String, 
tournaments: [{ 
    type: mongoose.Schema.Types.ObjectId, ref: "Tournament" 
}], 
avatar: [{ 
    type: mongoose.Schema.Types.ObjectId, ref: "Avatar" 
}] 
} 
}); 

表示第3次一個是我阿凡達模型:

var avatarSchema = mongoose.Schema({ 
imageName: String, 
imageRaceCategory: String, 
imagePath: String 
}); 

我想要做的是找到一個基於它的ID的比賽,然後填充播放器也是參加本次比賽的每位球員的頭像。但是,當我嘗試顯示玩家的頭像時,我會變得不確定。

這是我的查詢看起來像:

Tournament.findById(req.params._id).populate('players organizer players.local.avatar').exec(function(err, tournament){ 
    if(err){ 
    res.send(err) 
    }else{ 
helperFunctions.getUserDetails(req.params.userId, function(user){ 
         res.render('tournament/tournament-details.ejs',{ 
          user: req.user, 
          tournament: tournament, 
          userAvatar: user, 
          moment: moment, 
          enlistedInTournament: enlistedInTournament, 
          eligibleForTournament: eligibleForTournament, 
          allPlacesTaken: allPlacesTaken, 
          procentajOcupare: (tournament.players.length * (100/tournament.nrOfPlayers)) 
         }); 
      }); 
    } 
}); 

這也是我如何在視圖中顯示出來:

<%tournament.players.forEach(function(player){%> 
<img src="<%=player.local.avatar.imagePath + '/' + player.local.avatar.imageName"%>/> 
         <li> 
          <%= player.local.nickname + ', ' + player.local.race + ', ' + player.local.league%>, <a href="/profile-details/<%= player._id%>">Profil jucator</a> 
         </li> 
        <%});%> 

但是,我得到了一個未定義的avatar.imagePath和頭像。 imageName,一切工作正常。有一個更好的方法嗎?我錯過了什麼/做錯了什麼?先謝謝你!

回答

1

「您可以調用'populate'來輕鬆地將ObjectID解析到關聯的對象中,但不能調用'populate'來解析包含在該對象中的ObjectID此外,由於填充的對象在技術上不是文檔,你不能叫你連接到模式中的任何功能。雖然這絕對是一個嚴重的限制,它往往可以通過使用嵌套模式」

來避免請參考https://thecodebarbarian.wordpress.com/2013/06/06/61/替代品來解決您的問題

+0

謝謝你,Vitor! – war81 2014-11-27 17:09:19

0

由於未填充路徑players.local.avatar,您正在收到該問題。對於子填充,您需要循環訪問tournament.players並在其中填充local字段。