"use strict";
var mongoose = require('mongoose')
  , hm = require('./history-model');

module.exports = function historyPlugin(schema, options) {
  var customCollectionName  = options && options.customCollectionName;
  
  // Clear all history collection from Schema
  schema.statics.historyModel = function() {
    return hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options);
  };
  
  // Clear all history documents from history collection
  schema.statics.clearHistory = function(callback) {
    var History = hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options);
    History.remove({}, function(err) {
      callback(err);
    });
  };
  
  // Create an copy when insert or update
  schema.pre('save', function(next) {
    this.set('__v', undefined);
    
    var historyDoc = {};
    historyDoc['t'] = new Date();
    historyDoc['o'] = this.isNew ? 'i' : 'u';
    historyDoc['d'] = this;
    
    var history = new hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options)(historyDoc);
    history.save(next);
  });
  
  // Create an copy when insert or update
  schema.pre('remove', function(next) {
    this.set('__v', undefined);
    
    var historyDoc = {};
    historyDoc['t'] = new Date();
    historyDoc['o'] = 'r';
    historyDoc['d'] = this;
    
    var history = new hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options)(historyDoc);
    history.save(next);
  });
};

@@ -799,39 +799,62 @@
 next) %7B%0A    
-this.set('__v',
+ var d = this.toObject();%0A     d.__v =
  undefined);
@@ -843,33 +843,32 @@
 .__v = undefined
-)
 ;%0A    %0A    var h
@@ -977,36 +977,33 @@
 storyDoc%5B'd'%5D = 
-this
+d
 ;%0A    %0A    var h
@@ -1246,23 +1246,44 @@
     
-this.set('__v',
+var d = this.toObject();%0A    d.__v =
  und
@@ -1288,17 +1288,16 @@
 ndefined
-)
 ;%0A    %0A 
@@ -1403,20 +1403,17 @@
 %5B'd'%5D = 
-this
+d
 ;%0A    %0A 

Copy of mongoose doc without modified __v