azdfg1
azdfg1

Reputation: 109

Each template in meteor looping multiple times

I am learning how to use meteor and when I use the each template the app loops a random number of times. Does anyone know why?

JS

PlayersList = new Mongo.Collection('players');

PlayersList.insert({name: "David" , score:0});
PlayersList.insert({name: "Bob", score: 0});;
PlayersList.insert({name: "Wesley", score: -1000});

if(Meteor.isClient){
    Template.leaderboard.helpers({
        player: function(){
            return PlayersList.find();
        }
            });
}

and the HTML

<head>
    <title>LeaderBoard</title>
</head>

    <body>
        <h1>Leaderboard</h1>

        {{>leaderboard}}
    </body>
    <template name="leaderboard">
        {{#each player}}
            <li>{{name}}: {{score}}</li>
        {{/each}}
    </template>

Upvotes: 1

Views: 86

Answers (1)

David Weldon
David Weldon

Reputation: 64342

Do a meteor reset to clear your database and try this code instead:

PlayersList = new Mongo.Collection('players');

if (Meteor.isClient) {
  Template.leaderboard.helpers({
    player: function() {
      return PlayersList.find();
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function() {
    // if there are no players in the database
    if (PlayersList.find().count() === 0) {
      PlayersList.insert({name: "David", score: 0});
      PlayersList.insert({name: "Bob", score: 0});
      PlayersList.insert({name: "Wesley", score: -1000});
    }
  });
}

In the original code, players were inserted from both the client and the server (there was no Meteor.isServer guard). Every time a new client connected, and every time the server started, a new set of players would be inserted.

In the code above, we only insert new players when the server starts and only when there are no players in the database. This ensures the database is only seeded once after a reset.

Upvotes: 3

Related Questions