Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Tracking changes to fields using mongoose.js

Tracking changes to fields using mongoose.js

Problem

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.

Problem courtesy of: Bill

Solution

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

Solution courtesy of: Bill

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Tracking changes to fields using mongoose.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×