使用 mongoose.js 跟踪对字段的更改 [英] Tracking changes to fields using mongoose.js

查看:46
本文介绍了使用 mongoose.js 跟踪对字段的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出在使用 mongoose.js 时跟踪字段更改的最佳方法.例如,每次设置对象上的 name 字段时,我都想在该对象的历史记录中添加一个新条目(作为嵌入式文档),看起来像 { field: 'name',上一个:'foo',当前:'bar',日期:'3/06/2012 9:06 am' }.

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' }.

我开始尝试使用一个挂钩 .pre('save') 的插件,但是如果不从数据库中获取旧值,我无法确定哪些字段已被修改自己比较一下.然后我想我可以使用自定义设置器,但我遇到了同样的问题——我不知道修改了哪个字段.目前,我只能做这样的事情,将字段名称硬编码到 setter 中:

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.

推荐答案

看起来我错过了 'Document.modifiedPaths'.这正是我需要确定哪些字段已被修改.

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

这篇关于使用 mongoose.js 跟踪对字段的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆