Layover

[공식문서 나들이] Mongoose에서 .lean()은 무엇일까?

Kestrel 2023. 8. 14. 17:47

부트캠프 1차 프로젝트 할 때 lean()을 쓰는 것을 보았지만 나는 api 짜는 것도 바빠서 성능에 대한 것은 신경쓰지 못했다. 물론, 성능을 신경 써야할 만큼 큰 프로젝트가 아니었지만 이런 세심함이 나중에 성능적으로 큰 차이를 만들어 낸다고 생각한다. 

 

제일 정확한 것은 공식 문서이기에 공식 문서를 드다본다.


The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents. In this tutorial, you'll learn more about the tradeoffs of using lean().

 

- lean 옵션은 Mongoose가 새로운 문서를 만드는 것을 생략하도록 한다. 이 옵션은요청을 보다 빠르게 실행하고 메모리를 덜 먹는다. 그러나 결과 document는 일반 자바스크립트 객체이지 Mongoose의 document가 아니다. 이 튜토리얼에서는 lean() 옵션의 양날의 검 같은 면을 설명하고자한다.(의역 박아버림)



By default, Mongoose queries return an instance of the Mongoose Document class. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.

 

-  기본적으로 Mongoose 쿼리는 Document class의 인스턴스를 반환한다. Document는 바닐라 자바스크립트 객체보다 더 무겁다. 왜냐하면 Document는 변경을 감지하기 위해 내부 상태를 가지고 있기 때문이다. lean옵션은 그냥 자바스크립트 객체를 던져준다.



Under the hood, after executing a query, Mongoose converts the query results from POJOs to Mongoose documents. If you turn on the lean option, Mongoose skips this step.

 

- 쿼리가 실행되면 위와 같은 과정을 거쳐 일반 자바스크립트 객체가 Document가 된다. 만약 lean옵션을 선택하면 이 과정이 스킵되는 것이다.


 

한 줄 정리: 서비스 코드에서 데이터 변경할 것 아니면 lean()을 통해 그냥 쿼리를 통한 return값을 바닐라 자바스크립트 객체로 넘긴다. 예를 들어 get 메소드를 사용할 때 사용하고 post나 put, patch 사용할 때는 lean을 쓰면 안된다. 그냥 document는 상태를 가진다는 것만 기억해도 좋을 듯하다.