Skip to content

Instantly share code, notes, and snippets.

@dburles
Created March 2, 2014 02:47
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 dburles/9301112 to your computer and use it in GitHub Desktop.
Save dburles/9301112 to your computer and use it in GitHub Desktop.
var debug = function(str) {
console.log('counter-cache: ' + str);
};
Meteor.Collection.prototype.maintainCountOf = function(collection, field, counterField) {
var self = this;
// what is Meteor.users an instanceof ?
// if (! (collection instanceof Meteor.Collection))
// throw new Error("Expected first parameter to be a Meteor Collection");
if (! collection)
throw new Error("Missing parameter: collection");
if (! field)
throw new Error("Missing parameter: field name");
if (typeof counterField === 'undefined')
counterField = self._name + 'Count';
debug('setup counts of `' + collection._name + '` onto `' + this._name + '` with counter field `' + counterField + '`');
var modifier = { $inc: {}};
var decrement = function(_id) {
debug('decrement ' + _id);
if (! _id) return;
modifier[counterField] = 1;
self.update(_id, modifier);
};
var increment = function(_id) {
debug('increment ' + _id);
if (! _id) return;
modifier[counterField] = -1;
self.update(_id, { $inc: { teachersCount: 1 }});
};
collection.after.insert(function(userId, doc) {
fieldValue = _.dottedProperty(doc, field);
if (fieldValue)
increment(fieldValue);
});
collection.after.update(function(userId, doc, fieldNames, modifier, options) {
var self = this;
// console.log(modifier);
// console.log(fieldNames);
// console.log(this.previous);
// console.log(doc);
if (modifier.$set) {
var oldDoc = self.previous;
// LocalCollection._modify(doc, modifier);
var oldDocFieldValue = _.dottedProperty(oldDoc, field);
var newDocFieldValue = _.dottedProperty(doc, field);
if (oldDocFieldValue && newDocFieldValue !== oldDocFieldValue)
decrement(oldDocFieldValue);
increment(newDocFieldValue);
}
});
collection.after.remove(function(userId, doc) {
decrement(_.dottedProperty(doc, field));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment