I solved this with a collection that includes the count
for a query on a collection and inserts it under the connectionId.
For publications where the count is needed, it returns an array of cursors, including one for the counting collection.
So I declare the collection on client and server
CollectionCount = new Mongo.Collection("collection_count");
PagedCollection = new Mongo.Collection("paged_collection");
And define this function on the server, including some house keeping
function CollectionCountUpdate(connectionId, cursor) {
let collectionName = cursor._cursorDescription.collectionName;
let maxCount = cursor.count();
let ids = cursor.map((doc) => { return doc._id });
var cc = CollectionCount.findOne({ connectionId: connectionId, collection: collectionName });
var ccId = null;
if (cc) {
CollectionCount.update(cc._id, { $set: { maxCount: maxCount, ids: ids } });
ccId = cc._id;
} else {
ccId = CollectionCount.insert({ connectionId: connectionId, maxCount: maxCount, ids: ids, collection: collectionName });
}
return CollectionCount.find(ccId);
}
Meteor.onConnection(function (connection) {
const connectionId = connection.id;
connection.onClose(function () {
let c = CollectionCount.remove({ connectionId: connectionId });
if (Meteor.isDevelopment) console.log(`onClose ${connectionId} removed ${c}`);
});
});
Meteor.startup(function () {
//
// clear CollectionCount when server starts
//
CollectionCount.remove({});
});
In a publication I return two cursord, the requested cursor with the skip/limit and the count
Meteor.publish('somePaginatedCollection', function(query, options){
const self = this;
return [
CollectionCountUpdate(self.connection.id, Collection.find(query)),
PagedCollection.find(query, options),
];
});
On the client I now have easy access to the max count for pagination
Template.collection.onCreated(function(){
const instance = self;
instance.skip = new ReactiveVar(0);
instance.autorun(function(){
instance.subscribe('somePaginatedCollection', {whatever: true, iwant: {$gt:5}}, {skip: instance.skip.get(), limit: 10});
})
});
Template.collection.helpers({
maxCount(){
CollectionCount.findOne({collection:'paged_collection'});
}
});