簡體   English   中英

如何在Mongoose / MongoDB中存儲文檔的歷史記錄?

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

我有以下架構-

 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更新方法。

我已經在這個問題上工作了很多天,但找不到正確有效的解決方案。 任何解決此問題的方法將不勝感激。

您是否研究過midldeware hooks 通常,您想要的東西可以在那里處理。 例如查看貓鼬鈎子: 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() } });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM