title: Convert mongoose javascript code to typescript. This reference lost
body: <p>I started this new adventure in learning typescript. I took a nodejs project written of course in javascript and I'm converting it into typescript. My idea is to see all the benefits and to learn where are the problems, which pattern should I use and so on.<br>
  The project uses mongodb database with the mongoose javascript library and I'm struggling with how typescript transpilers the code. In simple words: <strong>I lose the this reference</strong>.<br>
  Here is good example that will cause the problem.<br></p>
  
  <pre><code> var personSchema = new mongoose.Schema({
    created: {
     type: Date,
  
     default: Date.now
    },
  
    updated:{
     type: Date,  
    },
   });
  
   personSchema.pre('save', function(next) {
  
   // Make sure updated holds the current date/time
  
   this.updated = new Date();
  
   next();
  
   });
  
   var Person = mongoose.model('Person', personSchema);
  </code></pre>
  
  <p>In the pre save function there is a <strong>this</strong> reference. The this is a reference of the current person with the updated property. Everything is fine. I saw this pattern in different examples<br><br>
  This is for me the first time that I'm working on nodejs project.<br>
  Here is how I tried a simple typescript conversion:</p>
  
  <pre><code> interface IPerson extends mongoose.Document{
    created:Date;
    updated:Date;
  }
  
  
   var personSchema = new mongoose.Schema({
    created: {
     type: Date,
     default: Date.now
   },
  
   updated: {
    type: Date
   }
  });
  
  personSchema.pre('save', (next) =&gt; {
   // Make sure updated holds the current date/time
   this.updated = new Date();
  
   next();
  });
  
  export =  mongoose.model&lt;IPerson&gt;('Person', personSchema);
  </code></pre>
  
  <p>After typescript transpilers the code the this is swapped with <strong>_this</strong>. On the top of the file you see <strong>var _this = this;</strong>. This is wrong. The new javascript file looses the reference of the person object.<br></p>
  
  <p>Can someone help me how to convert correctly the javascript into typescript? How should I solve this kind of problems? Is there some pattern?<br>
  My first impression is that sometimes is not straight forward convert javascript into typescript, but I really like it.</p>