2013-04-01 7 views
0

현재 배열에 저장 한 팀 ID 목록이 있습니다. teamIds. 나는 또한 내 Team의 키를 기반으로 팀을 찾는 몽구스 스키마에 함수 findByKey을 가지고있다. 코드에서 볼 수 있듯이 이전의 findByKey 바깥에 넣으면 각각의 새 코드를 새로 넣어야 만합니다. 제대로 작동하지 않습니다. 수있는 루프 배열 teamIds 통해 상기 배열의 각 Team 위해 루프의 일종으로 Team.findByKey 방법 바꾸어JavaScript/mongoose - 배열을 반복하여 객체 배열을 만듭니다.

I 데있어 문제. 새로운 토너먼트를 만들 수있는 기능을 개발 중입니다. 아이디어는 여기에 팀 ID 배열을 전달하고 각 ID를 반복하여 해당 팀을 검색하여 토너먼트를 만들려면 teamsList 배열에 추가하는 것입니다.

내 문제가되는 Team.findByKey 메서드에 Team 개체 배열을 만들려면 마지막 코드를 넣어야합니다. 어떻게하면이 문제를 해결하여 n 개의 팀을 찾고 각 팀을 찾고 Teams의 배열로 저장할 수 있습니까?

내 코드입니다 :

app.get('/tournament', function(req, res){ 
    function genMatches(nTeams) { 
     var matchArray = []; 
     while (nTeams > 1) { 
      nTeams = nTeams >> 1; 
      var matches = []; 
      for (var i = 0; i < nTeams; ++i) { 
       matches.push([]); 
      } 
      matchArray.push(matches); 
     } 
     return matchArray; 
    } 

    var teamIds = [ 
     1364472344972, 
     1363173222886, 
     1363007586845, 
     1363007557484 
    ] 

    var tournamentName = 'My Tournament'; 

    Team.findByKey(teamIds[0], function(err, team1) { 
     if(err) { 
      util.log("Error occured"); 
     } 
     if(!team1) { 
      util.log("The team does not exist"); 
     } 
     Team.findByKey(teamIds[1], function(err, team2) { 
      if(err) { 
      return util.log("Error occured"); 
      } 
      if(!team2) { 
      return util.log("The team does not exist"); 
      } 
      Team.findByKey(teamIds[2], function(err, team3) { 
      if(err) { 
       return util.log("Error occured"); 
      } 
      if(!team3) { 
       return util.log("The team does not exist"); 
      } 
      Team.findByKey(teamIds[3], function(err, team4) { 
       if(err) { 
       return util.log("Error occured"); 
       } 
       if(!team4) { 
       return util.log("The team does not exist"); 
       } 
       var teamList = [ 
       team1._id, 
       team2._id, 
       team3._id, 
       team4._id 
       ]; 

       var numRounds = Math.log(teamList.length)/Math.log(2); 

       var matches = genMatches(teamList.length); 
       for(var i = 0; i < matches[0].length; i++){ 
       matches[0][i] = [ teamList[i+i], teamList[i+(i+1)] ] 
       } 

       var tournament = new Tournament({ 
       name: tournamentName, 
       teams: teamList, 
       rounds: numRounds, 
       matches: matches 
       }); 

       res.send(tournament); 

      }); 
      }); 
     }); 
     }); 
    }); 

팀 스키마 :

'use strict'; 

var util = require('util'); 
var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var validatePresenceOf = function(value){ 
    return value && value.length; 
}; 

var toLower = function(string){ 
    return string.toLowerCase(); 
}; 

var getId = function(){ 
    return new Date().getTime(); 
}; 

/** 
    * The Team schema. we will use timestamp as the unique key for each team 
    */ 
var Team = new Schema({ 
    'key' : { 
    unique : true, 
    type : Number, 
    default: getId 
    }, 
    'name' : { type : String, 
       validate : [validatePresenceOf, 'Team name is required'], 
       index : { unique : true } 
      } 
}); 

/** 
    * Get complete team details for all the teams 
    */ 
Team.statics.getAll = function(cb){ 
    var query = this.find({}); 
    query.sort({key : -1}); 
    return query.exec(cb); 
}; 

Team.statics.findByKey = function(key, cb){ 
    return this.find({'key' : key}, cb); 
}; 

Team.statics.findByName = function(name, cb) { 
    return this.find({'name' : name}, cb); 
}; 

module.exports = mongoose.model('Team', Team); 

답변

1
당신은 하나 개의 질의에 4 개 팀을 찾기 위해 $in 연산자를 사용할 수

:

Team.find({key: {$in: teamIds}}, function (err, teams) { 
    ... 
}); 

하는 경우 어떤 이유로 붕괴하는 대신 findByKey 번을 여러 번 호출해야합니다. 이 모든 것을 하나의 $in에 넣으십시오. 더 정확하게하려면 라이브러리의 each 메소드를 사용하십시오.

+0

죄송합니다. 'Team' 스키마의 코드를 추가했습니다.이 스키마가 전혀 도움이되는지 확인할 수 있습니까? 나는 이렇게 할 방법이 있다면 나는 내 머리를 얻을 수있을 것이라고 생각하지 않기 때문에 다른 도서관 사용에 너무 열중하지 않습니다. 어떤 도움을 주셔서 감사합니다! – germainelol

+0

@ germainelol 나는 실제'key' 필드 이름을 사용하도록 나의 대답을 업데이트했습니다. – JohnnyHK

+0

감사합니다,이 작품과 나는 페이지에 팀의 배열을 출력 할 수 있습니다, 내 유일한 문제는이 기능에 의해 만들어진'팀'배열은이 함수 내에서만 사용할 수 있습니다. 어떻게하면이'/ tournament' 방법을 통해 나중에 사용할 수있는 '팀'배열을 만들 수 있을까요? – germainelol

관련 문제