Tracking changes to fields using mongoose.js

本小妞迷上赌 提交于 2021-02-07 12:40:03

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/9659979/tracking-changes-to-fields-using-mongoose-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!