3

What is an efficient approach to maintaining data history for models in Sails? For instance, how do we maintain the data if a user updates the database and we'd like to keep versions for reverting the data as it updates.

I've seen numerous examples of using a "changes" tag that keeps the date as a sub-tag. Is this the most efficient?

On model update we can copy previous information. Are there any better suggestions or links with examples?

{
   text:"This is the latest paragraph",
   changes:{
      text:{
          "1470685677694":"This was the paragraph",
          "1470685577694":"This was the original paragraph"
      }
   }
}

I am hoping to find a good solution to find / search and optimize this data to allow the user to revert if necessary.

Grant B
  • 31
  • 1

1 Answers1

0

You can define your model like the following and so you can preserve the history as well which you can use to restore any previous values.

api/models/Test.js

module.exports = {
  connectionName:"someMongodbServer",
  tableName:"test",
  autoCreatedAt:false,
  autoUpdatedAt:false,
  autoPk:false,
  attributes: {
    id:{
      type:"integer",
      primaryKey:true,
      autoIncrement:true
    },
    name:"string",
    history:{
      type:'json',
      defaultsTo:[]
    }
  },
  beforeCreate:function(value,cb){
    Test.count().exec(function (err, cnt) {
      if(err)
        return cb(err);
      value.id = cnt + 1;
      cb();
    });
  },
  beforeUpdate:function(values,cb){
    Test.native(function(err,collection){
      if(err)
        return cb(err);
      collection.findOne({_id:values.id},{history:0,_id:0},function(err,data){
        if(err)
          return cb(err);
        collection.updateOne({_id:values.id},{$push:{history:data}},function(err,res){
          if(err)
            return cb(err);
          console.log(res);
          cb();
        });
      })
    });
  }
};
vkstack
  • 1,582
  • 11
  • 24