Typescript mongoose static model method “Property does not exist on type”

后端 未结 5 967
囚心锁ツ
囚心锁ツ 2020-12-12 17:58

I am currently trying to add a static method to my mongoose schema but I can\'t find the reason why it doesn\'t work this way.

My model:

import * as          


        
5条回答
  •  清歌不尽
    2020-12-12 18:46

    For future readers:

    Remember that we are dealing with two different Mongo/Mongoose concepts: a Model, and Documents.

    Many Documents can be created from a single Model. The Model is the blueprint, the Document is the thing created according to the Model's instructions.

    Each Document contains its own data. Each also carries their own individual instance methods which are tied to its own this and only operate on that one specific instance.

    The Model can have 'static' methods which are not tied to a specific Document instance, but operate over the whole collection of Documents.

    How this all relates to TypeScript:

    • Extend Document to define types for instance properties and .method functions.
    • Extend the Model (of a Document) to define types for .static functions.

    The other answers here have decent code, so look at them and trace through the differences between how Documents are defined and how Models are defined.

    And remember when you go to use these things in your code, the Model is used to create new Documents and to call static methods like User.findOne or your custom statics (like User.hashPassword is defined above).

    And Documents are what you use to access the specific data from the object, or to call instance methods like this.save and custom instance methods like this.comparePassword defined above.

提交回复
热议问题