简体   繁体   English

如何在Mongoose / MongoDB中存储文档的历史记录?

[英]How to store history of the documents in Mongoose/MongoDB?

I have the following Schema - 我有以下架构-

 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); 

I want to store the update history of all the documents of this collection. 我想存储此集合的所有文档的更新历史记录。

For Example - 例如 -

If I change the name field of a lead from 'John' to 'Jane' then a record should be saved in a history table with the following schema - 如果我将线索的名称字段从“ John”更改为“ Jane”,则应使用以下模式将记录保存在历史记录表中-

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

I googled some plugins like mongoose-diff-history and it serves the purpose well but the only drawback was that it only worked with .save() method and not with mongodb updates methods. 我用歌搜索了一些插件,例如mongoose-diff-history ,它很好地达到了目的,但是唯一的缺点是它只适用于.save()方法,不适用于mongodb更新方法。

I have been working on this problem for so many days but couldn't find a correct and efficient solution. 我已经在这个问题上工作了很多天,但找不到正确有效的解决方案。 Any solutions to this problem will be very much appreciated. 任何解决此问题的方法将不胜感激。

Have you looked into the midldeware hooks ? 您是否研究过midldeware hooks Usually what you want could be handled there. 通常,您想要的东西可以在那里处理。 For example look into Mongoose hooks: http://mongoosejs.com/docs/middleware.html 例如查看猫鼬钩子: http : //mongoosejs.com/docs/middleware.html

You have basically "events" which allow you do intercept records just before "save" etc and do something (like in your case store/log somewhere). 您基本上具有“事件”,这些事件使您可以在“保存”等之前截取记录并执行某些操作(例如在您的案例存储/日志中的某处)。

Here is an example from their docs: 这是他们的文档中的一个示例:

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

Here is one for the 'update': 这是“更新”的一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM