简体   繁体   中英

MeteorJS and Mongo: Initial collection count is always 0

I have a self project of creating sudoku grid using meteor js. In this code, i try to fill in the database first before initialising the template and the template will just read from the database for existing values. below is my code for client side js:

Cells = new Mongo.Collection("cells");

if(Meteor.isClient) {
  Session.setDefault("colMax", 9);  
  Session.setDefault("rowMax", 9);

  Meteor.startup(function() { 
    for(var i = 0; i < Session.get("rowMax"); i++) {
      for(var j = 0; j < Session.get("colMax"); j++) {
        if(Cells.find({row: i, col: j}).count() == 0) {
          Cells.insert({
            value: -1,
            row: i,
            col: j,
            createdAt: new Date()
          });
        }
      }
    }
  });

  Template.createSudoku.helpers({
    rows: function() {
      var _rows = [];
      for(var i = 0; i < Session.get("rowMax"); i++) {
        _rows.push(Cells.find({row: i}, {sort: {col: 1}}));
      }
      return _rows;
    }
  });
}

And below is my html code

<body>
  <header>
    <h1>Sudoku</h1>
  </header>
  <table class="sudoku">
    {{> createSudoku}}
  </table>
  <button class="reset">reset</button>
</body>

<template name="createSudoku">
  {{#each rows}}
    {{> createRow cells=this}}
  {{/each}}  
</template>

<template name="createRow">
  <tr>
    {{#each cells}}
      {{> createCell}}
    {{/each}}
  </tr>
</template>

<template name="createCell">
  <td class="cell-{{row}}-{{col}}">{{value}}</td>
</template>

The issue is that, the table keeps multiplying every time I refresh the page. For additional info, I turned on the autopublish. Any hints to help me on this matter? Thanks!

the behavior is correct. The initial count of client side collection will always be 0, given that actual DB is stored on server side. The client DB gets populated over the course of time.

If want to insert some fixture data only once, standard procedure is to do it on server side.

However, if I misunderstand your use case and you still feel that for some reason, you must do it on client side, then do it inside a callback in your subscribe method.

Meteor.subscribe('faq', 
  /* onReady callback */
  function() {
    console.log(somecollection.find().count());
  }
)

See here: http://docs.meteor.com/#/full/meteor_subscribe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM