Skip to content

Instantly share code, notes, and snippets.

@fatso83
Created October 11, 2017 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fatso83/f133de40dac8f6530442f57224fec230 to your computer and use it in GitHub Desktop.
Save fatso83/f133de40dac8f6530442f57224fec230 to your computer and use it in GitHub Desktop.
Meteor pub-sub test.
// demonstrates how the local MiniMongo collection will only hold the required data necessary to fulfill
// queries on the returned data from the publication and that sort order is not prerserved, only the backing data
// tmp test
import {Mongo} from 'meteor/mongo';
import map from 'lodash/map';
console.log('start');
const Foos = new Mongo.Collection('foos');
if (Meteor.isServer) {
let counter = 0;
Foos.remove({});
Meteor.setInterval(() => {
counter++;
Foos.insert({val: counter, timestamp: Date.now()});
console.log('counter', counter);
if (counter % 10 === 0) console.log(Foos.find().length);
}, 1000);
Meteor.publish('vals', function ({sortOrder = 1}) {
return Foos.find({}, {limit: 10, sort: {val: sortOrder}});
});
}
function allVals() {
return map(Foos.find().fetch(), 'val');
}
if (Meteor.isClient) {
subscribe({sortOrder: 1});
window.getVals = printVals;
window.subscribe = subscribe;
}
let handle;
function subscribe({sortOrder}) {
if(handle) handle.stop();
handle = Meteor.subscribe('vals', {sortOrder});
Tracker.autorun(() => {
console.log(allVals());
});
}
function printVals() {
const vals = allVals();
const max = Math.max.apply(Math, vals);
console.log('val max', max, 'val count', vals.length, 'last ten',vals.slice(0, 10));
window.vals = vals;
window.map = map;
}
console.log('end');
@fatso83
Copy link
Author

fatso83 commented Oct 11, 2017

By calling subscribe({sortOrder:-1}) you will see that your local collection at times is 20 elements, not 10, with a mix of sorted and unsorted content. Also try a call with sortOrder: 1 to see it toggle back to a 10 item collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment