Stop 07 · Mongoose ODMTopics · 7/8

Virtuals and Instance Methods

Part of the MERN Stack Roadmap

In short

Some values are worth calculating instead of storing, like a full name or a discounted price. Some actions belong to the document itself, like checking a password. Virtuals and methods keep that logic on the model, where it belongs.

Virtuals are computed fields that are not stored, such as fullName, and instance methods add behaviour to documents, such as user.comparePassword().

The jaadu swipes a college ID card at a library turnstile while a small glowing calendar floats beside the card.

Think of it like this

The ID card and its owner

Your college ID card stores your date of birth, not your age. Anyone can work out your age from it whenever needed (a virtual). And only you can do certain things with the card, like swiping into the library (a method on that particular card).

Watch it happen

Virtual vs instance method

Virtual

  • A computed property, like user.fullName
  • Not stored in MongoDB
  • Can't be used in queries or sort
  • Shown in JSON with toJSON: { virtuals: true }

Instance method

  • A function on each document, like user.comparePassword()
  • Can be async and take arguments
  • Uses this to read the document's fields
  • Static methods live on the model instead

Use a virtual for a derived value, and a method for an action or a check.

The big ideas

What you need to know

Virtual getters

schema.virtual("fullName").get(function () { ... }) builds a value from stored fields.

Show them in JSON

Virtuals are hidden in res.json unless you set toJSON: { virtuals: true }. lean() results don't include them.

Instance methods

schema.methods.comparePassword = function (plain) { ... }. Call it on a fetched document.

Statics

schema.statics.findByEmail = function (email) { ... } adds a helper to the model, like User.findByEmail().

See it in code

Walk through the code

js
1const userSchema = new Schema(2  {3    firstName: String,4    lastName: String,5    email: { type: String, lowercase: true, unique: true },6    password: { type: String, select: false },7  },8  { toJSON: { virtuals: true } }9);10 11userSchema.virtual("fullName").get(function () {12  return [this.firstName, this.lastName].filter(Boolean).join(" ");13});14 15userSchema.methods.comparePassword = function (plain) {16  return bcrypt.compare(plain, this.password);17};18 19userSchema.statics.findByEmail = function (email) {20  return this.findOne({ email: email.toLowerCase() }).select("+password");21};22 23// Login24const user = await User.findByEmail(req.body.email);25if (!user || !(await user.comparePassword(req.body.password))) {26  throw new AppError(401, "INVALID_LOGIN", "Wrong email or password");27}28res.json({ id: user._id, name: user.fullName });

1/5Include virtuals whenever the document is turned into JSON.

A tidy login flow. The controller reads like a sentence because the model carries the logic.

Save yourself the pain

Common mistakes

Oops

Trying to query or sort by a virtual: User.find({ fullName: "Sneha Iyer" }).

Do this instead

Virtuals aren't stored. Query the real fields, or store the value if you need to search it.

Oops

Defining methods with arrow functions.

Do this instead

Arrow functions don't get this. Use function () {} so this is the document.

Your mission

Add behaviour to a model

~25 min

Quick check

Why doesn't fullName show up in the response from User.find().lean()?

Go deeper

  1. 1Add a fullName virtual and include virtuals in toJSON output.
  2. 2Write a comparePassword instance method that uses bcrypt.
  3. 3Add a static method like Product.findInStock() for a common query.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge