简体   繁体   中英

Mongoose method scope in TypeScript

I have a question about the scope of the object in the callback function of Mongoose methods. My employee has 'addresses'. When you call this 'method' it looks for the addresses in the addresses model.

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. The scope is on the object itself, however all examples show 'this'. This won't work in TypeScript as it thinks it is the main class.

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?

Since you don't want to capture the lexically scoped this , don't use => . Just use function .

There is a feature request to declare the meaning of this to be a particular type: https://github.com/Microsoft/TypeScript/issues/229

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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