【问题标题】:MeteorJS and Mongo: Initial collection count is always 0MeteorJS 和 Mongo:初始收集计数始终为 0
【发布时间】:2015-05-13 01:11:43
【问题描述】:

我有一个使用流星 js 创建数独网格的自我项目。在这段代码中,我尝试在初始化模板之前先填写数据库,模板只会从数据库中读取现有值。下面是我的客户端 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;
    }
  });
}

下面是我的html代码

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

问题在于,每次刷新页面时,表格都会不断增加。有关其他信息,我打开了自动发布。有什么提示可以帮助我解决这个问题吗?谢谢!

【问题讨论】:

    标签: javascript mongodb web meteor meteor-blaze


    【解决方案1】:

    行为是正确的。考虑到实际数据库存储在服务器端,客户端收集的初始计数将始终为 0。客户端数据库会随着时间的推移而填充。

    如果只想插入一些夹具数据一次,标准程序是在服务器端进行。

    但是,如果我误解了您的用例,并且您仍然认为出于某种原因,您必须在客户端执行此操作,然后在您的订阅方法的回调中执行此操作。

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

    请看这里:http://docs.meteor.com/#/full/meteor_subscribe

    【讨论】:

    • 我按照您在客户端代码中的建议添加了 Meteor.subscribe("cells", function() {...}),但 console.log 没有响应无济于事
    • 您是否删除了自动发布并添加了 Meteor.publish?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2013-04-22
    相关资源
    最近更新 更多