简体   繁体   中英

How to show the total count of items and a limit list of items on a same template

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'})
})

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 .

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'})
})

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