Virtual Properties, Instance Methods & Static Model Methods
Virtual Properties, Instance Methods & Static Model Methods
Mongoose allows adding domain behavior directly to your data models. Instead of scattering helper functions throughout controllers, you can attach Virtual Properties (computed properties not stored in MongoDB), Instance Methods (actions on a single document), and Static Methods (queries on the entire model).
1. Virtual Properties (Computed Attributes)
A Virtual Property is a logical field that can be read and written like a normal property, but is never persisted to the MongoDB database:
Virtual properties cannot be queried directly with Model.find({ fullName: '...' }) because they do not exist on disk in MongoDB!
2. Instance Methods (methods)
An Instance Method is a custom function available on every individual document instance:
3. Static Methods (statics)
A Static Method is a custom function attached directly to the compiled Model itself, ideal for specialized queries:
Multiple Choice Questions
User.find({ fullName: 'Sumit Sharma' }) when fullName is defined as a Mongoose virtual?res.json(user)?userSchema.methods.getTier = function() { ... }, what does this point to?One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.