I'm trying to figure out the best way to track changes to fields when using mongoose.js.  For example, every time the name field on an object is set, I want to add a new entry to that object's history (as an embedded document) that looks something like { field: 'name', previous: 'foo', current: 'bar', date: '3/06/2012 9:06 am' }.
I started by trying to use a plug-in that hooks .pre('save') but I can't figure out which fields have been modified without grabbing the old value from the database and comparing them myself.  Then I thought I could use custom setters, but I ran into the same problem - I don't know which field was modified.  Currently I'm left with doing something like this which hard codes the field name into to the setter:
var comment = new Schema({
  name : { type: String, set: trackName },
  history : [Change]
});
var trackName = function(val) {
  var change = new Change;
  change.field = 'name';
  change.previous = this.name;
  change.current = val;
  change.date = Date.now();
  this.history.push(change);
  return val;
}
But this means I need a custom setter for each field name that I want to track. I'm guessing there must be a better way to accomplish this.
Looks like i missed 'Document.modifiedPaths'. This does exactly what I need to determine which fields have been modified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With