简体   繁体   English

TypeScript中的猫鼬方法范围

[英]Mongoose method scope in TypeScript

I have a question about the scope of the object in the callback function of Mongoose methods. 我在Mongoose方法的回调函数中有关于对象范围的问题。 My employee has 'addresses'. 我的员工有“地址”。 When you call this 'method' it looks for the addresses in the addresses model. 当您调用此“方法”时,它将在地址模型中查找地址。

Javascript: 使用Javascript:

employeeSchema.methods.getAddresses = function (callback) { 
  addressModel.find({ _id: { $in: this.addresses } }, function (err, obj) {
    callback(obj);
  });
};

I want to make everything typed and have an issue with the 'this' scope in the function. 我想输入所有内容,并且函数中的“ this”范围有问题。 The scope is on the object itself, however all examples show 'this'. 作用域在对象本身上,但是所有示例都显示“ this”。 This won't work in TypeScript as it thinks it is the main class. 它在TypeScript中不起作用,因为它认为它是主类。

TypeScript: 打字稿:

employeeSchema.methods.getAddresses = (callback) => { 
  addressModel.find({ _id: { $in: this.addresses } }, (err, obj) => {
    callback(obj);
  });
};

I have the same issue with validation: 验证存在相同的问题:

accountSchema.path('email').validate(function (email, callback) {
  if (this.isNew || this.isModified('email')) {}
}

'This' is the account in the scope of the callback, but is there a way to actually pass the object to the callback? 'this'是回调范围内的帐户,但是有没有办法将对象实际传递给回调?

Since you don't want to capture the lexically scoped this , don't use => . 既然你不想要捕获的词法范围this ,不要使用=> Just use function . 只需使用function

There is a feature request to declare the meaning of this to be a particular type: https://github.com/Microsoft/TypeScript/issues/229 还有一个特征请求申报的含义this是一个特定类型: https://github.com/Microsoft/TypeScript/issues/229

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM