Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking changes to fields using mongoose.js

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.

like image 375
Bill Avatar asked Mar 11 '12 23:03

Bill


1 Answers

Looks like i missed 'Document.modifiedPaths'. This does exactly what I need to determine which fields have been modified.

like image 56
Bill Avatar answered Sep 23 '22 18:09

Bill