2014-06-16 168 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