[MongoDB] Mongoose - 인스턴스 메소드와 정적 메소드 (Instance Method & Static Method)

Zero·2023년 3월 14일
0

MongoDB

목록 보기
12/14

Instance Method 와 Static Method의 차이점

Instance method는 모델을 통해 생성된 인스턴스에서 사용가능한 메서드이고, statics method는 모델 자체에서 사용가능한 메서드이다.

const Product = mongoose.model("Product", productSchema);
  • Instance Method
    - 모든 각각의 인스턴스에 사용 가능한 메서드
    • `new Product(~~).save()
  • Static Method
    - Product 모델 자체에서 사용 가능한 메서드
    - Product.find()


Instance Method

화살표 함수가 아닌 기존의 function 표현식을 사용해야 한다 (함수의 값이 변하기 때문) , 인스턴스 메서드는 어떤 Product의 특정 인스턴스 하지만 화살표 함수를 쓰게 되면 해당 값을 가질 수 없다.

  • greet() 함수
productSchema.methods.greet = function() {
	console.log("hello World!!!");
};

const p = new Product({name: "bike bag", price:10})

p.greet()

--> Hello world!!!

  • 특정 Product 찾는 findProduct() 함수
const findProduct = async function() {
	const foundProduct = await Product.findOne({name : "Mountain Bike"});
	foundProduct.greet()'
};

findProduct();

--> Hello World

  • this.name 활용해보기
productSchema.methods.greet = function () {
	console.log("hello world");
  	console.log(' from ${this.name}`);
}

--> this 에 접근하면 각각의 인스턴스에 접근한다.



Static Method

  • 인스턴스가 아닌 모델 자체에 적용되는 정적 메소드 추가하기
  • 개별 인스턴스에 작동하는 것이 아니다.
// Static Method
productSchema.statics.fireSale = function () {
  return this.updateMany({}, { onSale: true, price: 0 });
};

const Product = mongoose.model("Product", productSchema);

Product.fireSale().then((res) => console.log(res));

db.products.find()

{ "_id" : ObjectId("63d66e483152c679c86f3ef8"), "name" : "Mountain Bike", "price" : 0, "onSale" : true, "categories" : [ "Outdoors" ], "qty" : { "online" : 0, "inStore" : 0 }, "v" : 0 }
{ "_id" : ObjectId("63d66ea2821c87ce860fe862"), "name" : "Tire Pump", "price" : 0, "onSale" : true, "categories" : [ "Cycling" ], "qty" : { "online" : 0, "inStore" : 0 }, "
v" : 0 }


- Static Method를 만드는 경우는 편하고 유용한 방식으로 찾거나 업데이트 또는 제거 작업을 위함
- 클래스나 모델 자체에 커스텀을 적용하고 메서드 추가
- 다시 말해 `fireSale`은 특정한 Product와 관련있는 것이 아니라 모든 Product 즉, 전체적인 Product 모델과 관련 있다.

0개의 댓글