将mongoose javascript代码转换为typescript.此引用丢失

Convert mongoose javascript code to typescript. This reference lost

本文关键字:引用 typescript mongoose javascript 代码 转换      更新时间:2023-09-26

我开始了学习打字的新冒险。我参加了一个当然是用javascript编写的nodejs项目,并将其转换为typescript。我的想法是看到所有的好处,了解问题在哪里,我应该使用哪种模式等等。
该项目使用mongodb数据库和mongose javascript库,我很难理解typescript如何转换代码。简单地说:我失去了这个引用
以下是导致问题的好例子

 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);

在预保存功能中,有一个this引用。这是具有更新属性的当前人员的引用。一切都很好。我在不同的例子中看到了这种模式

这是我第一次从事nodejs项目
以下是我如何尝试简单的打字脚本转换:

 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) => {
 // Make sure updated holds the current date/time
 this.updated = new Date();
 next();
});
export =  mongoose.model<IPerson>('Person', personSchema);

在typescript transpiler代码之后,this将与_this交换。在文件的顶部,您可以看到var_this=this。这是错误的。新的javascript文件丢失了person对象的引用

有人能帮我如何正确地将javascript转换为typescript吗?我应该如何解决这类问题?有什么图案吗
我的第一印象是,有时不能直接将javascript转换为typescript,但我真的很喜欢它。

试试这个:

var personSchema = new mongoose.Schema({
    created: {
       type: Date,
       default: Date.now
    },
    updated: {
        type: Date
    }
    saveHandler(next) {
        // Make sure updated holds the current date/time
        this.updated = new Date();
        next();
    }
});
personSchema.pre('save', personSchema.saveHandler);

所以这个问题有点老了,我不确定你是否已经解决了它,但还没有选择答案,所以这可能会帮助其他人。

我自己也为此挣扎了一段时间,我相信我已经想通了。

此外,请考虑到每个代码都是不同的,因此这可能不会在任何情况下都解决问题,但请尝试取消箭头函数。请改用正则函数。

ES6的箭头函数使用词法范围,因此在这种情况下,"this"并不是您实际期望的。很可能,嗯。。。未定义,或者Schema本身。它没有指向文档,因此找不到它的任何方法和/或属性。