티스토리 뷰

Backend/꾸준히 TIL

[mongodb/mongoose] methods vs method

개발하는 후딘 2022. 8. 28. 03:06
728x90
반응형

객체안에 메소드 정의할 때는 mongoose모듈을 불러와서 mongoose.methods 로 했습니다.

mongoose의 Schema 내부 타입스크립트 코드를 한번 뜯어보니까 method 도 있다는걸 알게됐습니다. 

mongoose.methodmongoose.methods 의 용도와 의미가 무엇인지 알아보기로 했습니다.

 

(1) mongoose.method

소스를 깠을 때는 의미는 다음과 같습니다.

Adds an instance method to documents constructed from Models compiled from this schema.

이 스키마에서 컴파일된 모델로 작성된 문서에 인스턴스 메서드를 추가 합니다.

 

(2) mongoose.methods

Object of currently defined methods on this schema.

이 스키마에 현재 정의된 메서드의 객체 입니다.

 

 


(추가) Mongoose 'static' methods vs 'instance' methods

static 메소드 는 클래스 인스턴스 객체를 정의하지 않아도 불러올 수 있는 메소드 입니다.

반면에 instance 메소드는 클래스 인스턴스 객체를 정의해야 불러올 수 있는 메소드 입니다.

const pokemon = new mongoose.Schema({});

// static method
pokemon.statics.getAllWithType = function(type) {
	this.find({type: type});
}

// instance method
pokemon.methods.sayName = function () {
	console.log(this.name);
}


const pokemonModel = mongoose.model('pokemon', pokemon);

// define instance
const squirtle = new pokemonModel({name: "꼬부기"});

// use static method
pokemonModel.getAllWithType("물");

// use instance method
squirtle.sayName();

 

[참고]

 

Mongoose 'static' methods vs. 'instance' methods

I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation: We may also define our own custom document instance methods too. // define a ...

stackoverflow.com

 

< mongoose: method >

https://mongoosejs.com/docs/api.html#schema_Schema-method

 

Mongoose v6.5.3: API docs

 

mongoosejs.com

 

<mongoose: methods >

https://mongoosejs.com/docs/guide.html#methods

 

Mongoose v6.5.3: Schemas

If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 5.x to 6.x please take a moment to read the migration guide. Everything in Mongoose starts with a Schema. Each schema ma

mongoosejs.com

 

728x90
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함