MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Virtual Properties, Instance Methods & Static Model Methods0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
3.1Mongoose Connection Lifecycle, Schemas & Compiled Models3.2Built-in & Custom Schema Validations with Custom Error Messages3.3Pre and Post Middleware Hooks (Document & Query Middleware)3.4Virtual Properties, Instance Methods & Static Model Methods
HomeTutorialsMongoDB & MongooseVirtual Properties, Instance Methods & Static Model Methods
One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling

Virtual Properties, Instance Methods & Static Model Methods

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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:

1import { Schema, model } from 'mongoose';
2 
3const userSchema = new Schema({
4 firstName: { type: String, required: true },
5 lastName: { type: String, required: true },
6 birthDate: { type: Date, required: true }
7}, {
8 // Ensure virtuals are included when converting to JSON or Objects
9 toJSON: { virtuals: true },
10 toObject: { virtuals: true }
11});
12 
13// Define virtual getter for 'fullName'
14userSchema.virtual('fullName').get(function() {
15 return `${this.firstName} ${this.lastName}`;
16});
17 
18// Define virtual getter for calculated 'age'
19userSchema.virtual('age').get(function() {
20 const diffMs = Date.now() - this.birthDate.getTime();
21 const ageDt = new Date(diffMs);
22 return Math.abs(ageDt.getUTCFullYear() - 1970);
23});

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:

1import bcrypt from 'bcrypt';
2 
3// Method to verify passwords during authentication
4userSchema.methods.comparePassword = async function(candidatePassword) {
5 // 'this.password' contains the stored bcrypt hash
6 return await bcrypt.compare(candidatePassword, this.password);
7};
8 
9// Method to generate a password reset token
10userSchema.methods.createPasswordResetToken = function() {
11 const resetToken = crypto.randomBytes(32).toString('hex');
12 this.passwordResetToken = crypto.createHash('sha256').update(resetToken).digest('hex');
13 this.passwordResetExpires = Date.now() + 10 * 60 * 1000; // 10 minutes
14 return resetToken;
15};

3. Static Methods (statics)

A Static Method is a custom function attached directly to the compiled Model itself, ideal for specialized queries:

1// Custom static method to find top-rated active courses
2courseSchema.statics.getFeaturedCourses = function(limit = 6) {
3 // 'this' refers to the Course model
4 return this.find({ isPublished: true, rating: { $gte: 4.5 } })
5 .sort('-rating')
6 .limit(limit)
7 .populate('instructor', 'name avatar');
8};
9 
10// Invoking static method:
11const topCourses = await Course.getFeaturedCourses(10);

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Where are Mongoose Virtual Properties stored?
Question 2
Why can't you run User.find({ fullName: 'Sumit Sharma' }) when fullName is defined as a Mongoose virtual?
Question 3
What is the difference between an Instance Method and a Static Method in Mongoose?
Question 4
Which schema option must be set to ensure virtual fields are displayed when sending a document via res.json(user)?
Question 5
In an instance method userSchema.methods.getTier = function() { ... }, what does this point to?

Next Lesson

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

Previous LessonNext Lesson
Pre and Post Middleware Hooks (Document & Query Middleware)One-to-Few (Embedded) vs One-to-Many (Referenced) Data Modeling

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext