1

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?

1
  • Why not just pass in addresses into your method as a parameter? (addresses, callback)...then the caller will use "this.addresses" Commented Sep 29, 2014 at 14:44

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Oke I will use function() and cast this to the typed object until then. Thanks
just a tip : prefer the term assert instead of cast as there isn't any runtime support

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.