programing

몽구스 '정적'방법 대 '인스턴스'방법

goodcopy 2021. 1. 15. 19:19
반응형

몽구스 '정적'방법 대 '인스턴스'방법


이 질문과 유사한 생각 이 하나 있지만, 용어는 다르다. Mongoose 4 문서에서 :

사용자 정의 문서 인스턴스 메서드도 정의 할 수 있습니다.

// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

이제 모든 동물 인스턴스에 사용할 수있는 findSimilarTypes 메서드가 있습니다.

그리고:

모델에 정적 메서드를 추가하는 것도 간단합니다. 우리의 animalSchema로 계속 :

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
  return this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
  console.log(animals);
});

정적 메서드를 사용하면 각 동물 인스턴스 findByName에도 사용할 수 있는 메서드 가있는 것 같습니다 . 스키마에서 staticsmethods개체는 무엇입니까 ? 차이점은 무엇이며 왜 다른 하나를 사용합니까?


statics모델에 정의 된 방법입니다. methods문서 (인스턴스)에 정의되어 있습니다.

다음 과 같은 정적 메서드를 사용할 수 있습니다 Animal.findByName.

const fido = await Animal.findByName('fido');
// fido => { name: 'fido', type: 'dog' }

다음과 같은 인스턴스 메서드를 사용할 수 있습니다 fido.findSimilarTypes.

const dogs = await fido.findSimilarTypes();
// dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]

하지만 Animals.findSimilarTypes()동물은 모델이기 때문에 그렇게하지 않을 것 입니다. "유형"이 없습니다. Animals 모델에는 존재하지 않는이 findSimilarTypes필요합니다 this.type. 모델에 정의 된대로 문서 인스턴스에만 해당 속성이 포함됩니다.

마찬가지로 모든 문서를 검색해야 하고 문서 일 뿐이 fido.findByName므로 ¹ 그렇게하지 않습니다.findByNamefido

¹Well는, 기술적으로는 , 인스턴스 않기 때문에 컬렉션 (에 액세스 할 수 있습니다 this.constructor또는 this.model('Animal'))하지만 인스턴스에서 모든 속성을 사용하지 않는 인스턴스 메서드를 가지고 (적어도이 경우에) 의미가 없다. ( 이것을 지적한 @AaronDufour 에게 감사드립니다 )


데이터베이스 로직은 데이터 모델 내에 캡슐화되어야합니다. Mongoose는이를 수행하는 방법과 통계라는 두 가지 방법을 제공합니다. 메서드는 문서에 인스턴스 메서드를 추가하는 반면 Statics는 모델 자체에 정적 "클래스"메서드를 추가합니다. static 키워드는 모델에 대한 정적 메서드를 정의합니다. 정적 메서드는 모델의 인스턴스에서 호출되지 않습니다. 대신 모델 자체에서 호출됩니다. 이들은 종종 객체를 생성하거나 복제하는 함수와 같은 유틸리티 함수입니다. 아래 예와 같이 :

const bookSchema = mongoose.Schema({
  title: {
    type : String,
    required : [true, 'Book name required']
  },
  publisher : {
    type : String,
    required : [true, 'Publisher name required']
  },
  thumbnail : {
    type : String
  }
  type : {
    type : String
  },
  hasAward : {
    type : Boolean
  }
});

//method
bookSchema.methods.findByType = function (callback) {
  return this.model('Book').find({ type: this.type }, callback);
};

// statics
bookSchema.statics.findBooksWithAward = function (callback) {
  Book.find({ hasAward: true }, callback);
};

const Book = mongoose.model('Book', bookSchema);
export default Book;

for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/


Pls also check this documentation from mongoosejs about Documents vs Models

[https://mongoosejs.com/docs/documents.html][1]

it helped me to have a better understanding of 'static' methods vs. 'instance' methods

ReferenceURL : https://stackoverflow.com/questions/29664499/mongoose-static-methods-vs-instance-methods

반응형