germainelol
germainelol

Reputation: 3331

JavaScript / mongoose - Loop through an array to create array of Objects

At the moment I have a list of Team ID's which I have stored in the array teamIds. I also have a function findByKey in my Team mongoose schema which finds a Team based on its key. As you can see from the code I have to put each new Team.findByKey inside the previous one, if I put it outside of the previous findByKey it doesn't function correctly.

I'm having problems putting the Team.findByKey methods into some sort of for loop which can loop through the array teamIds and for each Team in the array. I am developing the function to create a new tournament, the idea is that you pass an array of teamIds to here, and it loops through each ID, searching for that Team and adding it to a teamsList array in order to create the tournament.

I need to put the last bit of code to create the array of Team objects into the last Team.findByKey method which is my problem. How would I fix this so that I can pass it n amount of teams and find each team and store it as an array of Teams?

This is my code:

  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);

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

Team schema:

'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);

Upvotes: 0

Views: 1441

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use the $in operator to look up your four teams in one query:

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

If for some reason you need to call findByKey multiple times instead of collapsing it all into a single $in, look at using the async library's each method to do that more cleanly.

Upvotes: 1

Related Questions