Virtuals vs Methods in Mongoose

后端 未结 2 844
误落风尘
误落风尘 2020-12-28 20:58

I understand that static methods are Class Methods, and that methods are Instance Methods and that Virtuals

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 21:59

    I was trying to figure out when to use Virtuals and when to use Instances and I would summarize it like this:

    Statics - For methods (operations) that require no instance of a model to be run. Or, generic operations against the model.

    e.g. finding a document, listing all documents.

    Instances - For methods (operations) that do require an instance of the model to be present.

    e.g. finding or retrieving data based on the current instance data. Like other documents associated with the instance. model.getRelatedDocs()

    Virtuals - For reading properties of the model and making it clear at code level that those are properties/attributes and not methods. Also, for composed properties based on data that is already loaded in the instance. e.g. the trypical full name example.

提交回复
热议问题