2014-06-16 219 views
0

我得到了貓鼬3個數據庫模型,看起來像這樣:貓鼬填充文件

//profile.js 
var ProfileSchema = new Schema({ 
    username: { type: String, required: true },     
    password: { type: String, required: true },     
    matches: [{ type: Schema.Types.ObjectId, ref: 'Match' }] 
}); 

//match.js 
var MatchSchema = new Schema({ 
    scores:  [{ type: Schema.Types.ObjectId, ref: 'Score', required: true }], 
}); 

//score.js 
var ScoreSchema = new Schema({ 
    score:  {type: Number, required: true}, 
    achivement: [{type: String, required: true}], 
}); 

,我要儘量填充

Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) }) 
      .populate('matches') 
      .populate('matches.scores') 
      .exec(function(err, profile) { 
       if (err) {...} 
       if (profile) { 
        console.log(profile); 
       } 
      }); 

配置文件中的比賽得到填充,但我不明白的分數在匹配填充。這在貓鼬中不被支持,或者我做錯了什麼?填充給我這個:

{ 
    user_token: "539b07397c045fc00efc8b84" 
    username: "username002" 
    sex: 0 
    country: "SE" 
    friends: [] 
    -matches: [ 
     -{ 
      __v: 1 
      _id: "539eddf9eac17bb8185b950c" 
      -scores: [ 
       "539ee1c876f274701e17c068" 
       "539ee1c876f274701e17c069" 
       "539ee1c876f274701e17c06a" 
      ] 
     } 
    ] 
} 

但我想填充比賽數組中的比分數組。我可以這樣做嗎?

回答

0

是的,你是對的。我嘗試使用鏈接的填充我有相同的輸出。

對於您的查詢,請使用async.js,然後填入下面提到的方法。

欲瞭解更多詳情請看看這個代碼snippet。根據您的查詢,它是一個工作,測試,示例代碼。 請仔細閱讀已註釋的代碼,以便更好地理解下面的代碼和提供的代碼段的鏈接。

//Find the profile and populate all matches related to that profile 
Profile.findOne({ 
    _id: mongoose.Types.ObjectId(profile_id) 
}) 
.populate('matches') 
.exec(function(err, profile) { 
    if (err) throw err; 

    //We got the profile and populated matches in Array Form 
    if (profile) { 
     // Now there are multiple Matches 
     // We want to fetch score of each Match 
     // for that particular profile 

     // For each match related to that profile 
     async.forEach(profile.matches, function(match) { 
      console.log(match, 'match') 
      // For each match related to that profile 
      // Populate score achieved by that person 
      Match.find({ 
       _id:match.id 
      }) 
      .populate('scores', 'score') 
      .exec(function (err, score) { 
       if (err) throw err; 

       // here is score of all the matches 
       // played by the person whose profile id 
       // is passed 
       console.log(score); 
      }) 
     }) 
    } 
}); 
0
Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) }) 
     .populate('matches.scores') 
     .exec(function(err, profile) { 
      if (err) {...} 
      if (profile) { 
       console.log(profile); 
      } 
     }); 
+0

這個職位是標記爲低質量。請編輯更多信息。僅限代碼和「嘗試這個」的答案是不鼓勵的,因爲它們不包含可搜索的內容,也不解釋爲什麼有人應該「嘗試這個」。 – Paritosh