몽구스 모듈을 이용해 스키마와 메소드를 정의하던 중 다음과 같은 에러가 발생했다.
this.find is not a function
에러가 발생한 코드는 다음과 같다.
userSchema.static('findById', (id, callback) => {
return this.find({id:id}, callback);
});
userSchema.static('findAll', (callback) => {
return this.find({}, callback);
});
이는 this binding에 대한 개념이 없어서 발생한 문제였다.
기존 JavaScript에선 함수 선언 시 this에 바인딩할 객체가 동적으로 결정되었다.
하지만, arrow function을 사용하면 바인딩할 객체가 정적으로 결정된다. 즉, 함수 안의 this가 상위 스코프의 this를 가리키게 되는 것이다.
위에서 선언한 this는 메소드를 호출한 객체와 바인딩하기 위해 사용한 코드로, 다음과 같이 full function의 형태로 코드를 수정한다.
userSchema.static('findById', function(id, callback) {
return this.find({id:id}, callback);
});
userSchema.static('findAll', function(callback) {
return this.find({}, callback);
});
이로써 메소드 내부 코드에서 사용된 this는 해당 메소드를 호출한 객체로 바인딩된다.
참고
1. arrow function this binding
2. this binding
velog.io/@litien/Javascript-This-Binding
3. why in mongoose find not working?
dev-qa.com/272940/why-in-mongoose-find-not-working
'트러블슈팅' 카테고리의 다른 글
[트러블슈팅] ER_CON_COUNT_ERROR: Too many connections (1) | 2021.05.06 |
---|---|
[트러블슈팅] Uncaught ReferenceError: kakao is not defined (5) | 2021.04.29 |
[스크랩] 누구나 한 번쯤은 띄워본 JavaScript 에러 TOP 10. (0) | 2021.02.20 |
[트러블슈팅] FastAPI CORS 에러 (0) | 2021.02.13 |
[트러블슈팅] LF/CRLF 에러 (0) | 2021.01.20 |