Meteor Collections.count() 在 UI 上太慢了

Meteor Collections.count() too slow on UI

我在我的流星项目中做了一个简单的 Publish/subscribe,每当用户登陆主页时,我都必须显示总用户数。用户在 15000 左右。现在在模板助手中,我将代码编写为,

客户端

Template.voters.helpers({
  voters : function() {
   return voters.find({});
  },
  count :  voterscount
  });

然后在服务器端

voters = new Mongo.Collection("voters");
voterscount = function() {
    return voters.find({}).count();
}

Meteor.publish('voters', function() {
    return voters.find({});
  });

Meteor.publish('voterscount', function() {
    return voterscount;
  });
  1. 我收到的输出是 UI 上的计数从 0 开始到 15000,这很烦人。
  2. 我不想汇总 UI 上的数字,并且应该在刷新页面时将 UI 上的静态计数显示为 15000。
  3. 为什么这么慢呢。在生产中,我将收集大约 1000 万份文件。这是很大的缺点。有什么帮助吗?

这是通用出版物的一个很好的用例,即自动发送给所有客户的出版物。

服务器:

stats = new Mongo.collection('stats'); // define a new collection
function upsertVoterCount(){ 
  stats.upsert('numberOfVoters',{ numberOfVoters: voters.find().count() });
}
upsertVoterCount();

Meteor.publish(null,function(){ // null name means send to all clients
  return stats.find();
});

var voterCursor = voters.find();
voterCursor.observe({
  added: upsertVoterCount,
  removed: upsertVoterCount
});

然后在客户端上,您可以随时通过以下方式获取选民人数:

var nVoters = stats.findOne('numberOfVoters').numberOfVoters;

服务器-publish.js

function upsertVoterCount(){ 
   voterscount.upsert('numberOfVoters',
     { 
        numberOfVoters : voters.find().count() 
     });
}


// null name means send to all clients
Meteor.publish(null ,function() { 
    upsertVoterCount();
    return voterscount.find();
});

var voterCursor = voters.find();

voterCursor.observe({
  added: upsertVoterCount,
  removed: upsertVoterCount
});

LIB-collection.js

// define a new collection
voterscount = new Mongo.Collection('voterscount'); 

客户-home.js

Template.voter.helpers({
  count :  function() {
    return voterscount.findOne().numberOfVoters;
  }
});