【问题标题】:How to store history of the documents in Mongoose/MongoDB?如何在 Mongoose/MongoDB 中存储文档的历史记录?
【发布时间】:2019-01-05 11:54:03
【问题描述】:

我有以下架构 -

const leadSchema = new Schema(
  {
 
    emails: [{ type: Email, default: null }],
    name: {  type: String },
    country: { type: String },

    city: { type: String, index: true },
    source: {
      type: Number,
      min: 1,
      max: leadConfig.sources.length,
      required: true
    },
    course: { type: Schema.Types.ObjectId, ref: 'courses',required: true},

    gender: { type: String, enum: leadConfig.gender },
    status: {type: Schema.Types.ObjectId, ref: 'status' },
 
    dob: Date,
    parent_name: String,
    counselor: { type: Schema.Types.ObjectId, ref: 'users', default: null },

    consultant_amount: { type: Number, min: 0, default: 0 },
    consultant_amount_paid: { type: Number, min: 0, default: 0 },
    loan: { type: Boolean, default: false },
    reported: { type: Boolean, default: false },
    scholarship: { type: Number, default: 0 },
    student_id: { type: Number, default: null },
    next_interection_deadline: { type: Date, default: null },
    session: { type: Schema.Types.ObjectId, ref: 'session' }
  },
  { timestamps: true }
);
module.exports = mongoose.model('leads', leadSchema);

我想存储这个集合的所有文档的更新历史。

例如-

如果我将潜在客户的名称字段从“John”更改为“Jane”,则记录应保存在具有以下架构的历史记录表中 -

{
_id:(ObjectId),
collectionName:"lead"
column_name:"name"
oldValue - 'John',
newValue - 'Jane'
updateAt -  Date()
}

我搜索了一些插件,例如mongoose-diff-history,它很好地达到了目的,但唯一的缺点是它只适用于 .save() 方法而不适用于 mongodb 更新方法。

我在这个问题上工作了这么多天,但找不到正确有效的解决方案。对此问题的任何解决方案将不胜感激。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您查看过midldeware hooks 吗?通常你想要的东西都可以在那里处理。例如查看 Mongoose 钩子:http://mongoosejs.com/docs/middleware.html

    您基本上拥有“事件”,允许您在“保存”等之前截取记录并执行某些操作(例如在您的案例存储/记录某处)。

    这是他们文档中的一个示例:

    var schema = new Schema(..);
    schema.pre('save', function(next) {
      // do stuff
      next();
    })
    

    这是一个“更新”:

    schema.pre('update', function() {
       this.update({},{ $set: { updatedAt: new Date() } });
    });
    

    【讨论】:

    • 我试过了,但没用。在 pre 'save' 方法中,“this”只保存更新后的值,而不保存旧值。
    • 你确定吗?你看过这篇文章了吗:stackoverflow.com/questions/11436071/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多