Reputation: 3964
I have two sections on my page.
The first section has a limited list of items. The Second section has a total count of items (recordsCount).
When a server adds a new item I see the list of items is updated but the total count has an old value.
Tracks = new Mongo.Collection('tracks')
Client:
Meteor.subscribe('tracks')
Meteor.call('records', function(err, data) {
Session.set('_records', data)
})
Template.tracks.helpers({
tracks: function() {
return Tracks.find()
},
recordsCount: function() {
return Session.get('_records')
}
})
Server:
Meteor.publish('tracks', function() {
return Tracks.find({}, {limit: 100})
})
Meteor.methods({
records: function() {
return Tracks.find({}).count()
}
})
var CronManager = new Cron(10000)
CronManager.addJob(1, function() {
Tracks.insert({filed1: 'test'})
})
Upvotes: 0
Views: 438
Reputation: 3964
I've investigated the solution with the publish-counts package. In my case it is the very heavy package. It was loading CPU all the time. I've replace my server side code to use a collection with count field.
Common:
Counter = new Mongo.Collection('count')
Server: Meteor.Publish('count', function() { return Counter.find() })
if(Counter.find().count() === 0) Counter.insert({count: Tracks.find().count()})
var CronManager = new Cron(10000)
CronManager.addJob(1, function() {
Counter.update({}, {$inc: {count: 1}})
Tracks.insert({filed1: 'test'})
})
Upvotes: 0
Reputation: 151936
If you just want to efficiently bring counts into your app, check out the publish-counts package.
Meteor.publish('posts', function(author) {
var cursor = Tracks.find(...);
Counts.publish(this, 'tracks-count', cursor, {nonReactive: true});
});
The nonReactive
options sends the count only on demand. This can be useful if you don't really need real-time counts, since most apps can do fine with updates every few seconds. That will save a lot of CPU.
Template.tracks.helpers({
tracks: function() {
return Counts.get('posts-count')
}
});
Hattip to Arunoda's excellent chapter on this from Bulletproof Meteor, Counting Documents.
Upvotes: 1