2

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 -

{
_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.

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.

Malkeet Singh
  • 33
  • 1
  • 4

1 Answers1

0

Have you looked into the midldeware hooks? Usually what you want could be handled there. For example look into Mongoose hooks: 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() } });
});
Akrion
  • 18,117
  • 1
  • 34
  • 54
  • I tried but it didn't work. In the pre 'save' method, "this" holds the updated values only, not the old values. – Malkeet Singh Jul 31 '18 at 04:23
  • Are you sure? Did you read this post: https://stackoverflow.com/questions/11436071/does-mongoose-provide-access-to-previous-value-of-property-in-presave – Akrion Jul 31 '18 at 05:14