Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Schemas and Models

Mongoose Virtuals, Getters and Setters

Compute fields without storing them: Mongoose virtuals, getters, setters, virtual populate and when to include them in JSON output.

Not every value belongs in the database. A full name is just a first and last name joined; a price shown with a currency symbol is just a number formatted. Storing these duplicates data and invites inconsistencies. Mongoose gives you three tools to compute values on the fly: virtuals, getters and setters.

Virtuals

A virtual is a property that exists on the document but is not stored in MongoDB. You define it on the schema with schema.virtual(name) and give it a get function, an optional set function, or both.

JavaScript
const personSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
});

personSchema.virtual('fullName').get(function () {
  return `${this.firstName} ${this.lastName}`;
});

const Person = mongoose.model('Person', personSchema);

const p = new Person({ firstName: 'Ada', lastName: 'Lovelace' });
console.log(p.fullName); // 'Ada Lovelace'

Use a regular function, not an arrow function, because Mongoose calls it with the document as this.

A virtual can also have a setter. The setter receives the assigned value and updates real fields:

JavaScript
personSchema.virtual('fullName')
  .get(function () { return `${this.firstName} ${this.lastName}`; })
  .set(function (value) {
    const [first, ...rest] = value.split(' ');
    this.firstName = first;
    this.lastName = rest.join(' ');
  });

p.fullName = 'Grace Brewster Hopper';
console.log(p.firstName); // 'Grace'
console.log(p.lastName);  // 'Brewster Hopper'
Node.js A virtual property (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line is the key point: the virtual is not among the stored keys.

Limits of virtuals

Because virtuals are not stored, you cannot query by them. Person.find({ fullName: 'Ada Lovelace' }) matches nothing, since MongoDB has no such field. Query the real fields (firstName and lastName) instead, or store a computed field if you need to search it.

Showing virtuals in JSON

Virtuals are not included when you call toJSON() or toObject() unless you ask. Enable them in the schema options:

JavaScript
const personSchema = new mongoose.Schema(
  { firstName: String, lastName: String },
  { toJSON: { virtuals: true }, toObject: { virtuals: true } }
);

Without this, res.json(person) will not contain fullName, a common source of confusion.

The id virtual

Every schema gets a virtual id that returns _id as a string. doc.id is the quick way to get '6733...' instead of an ObjectId. You can switch it off with the id: false schema option.

Getters

A getter transforms a stored value when you read it. It is part of the field definition:

JavaScript
const productSchema = new mongoose.Schema({
  priceCents: {
    type: Number,
    get: (v) => (v / 100).toFixed(2),
  },
});

Reading product.priceCents now returns the string '19.99' for a stored value of 1999. The database still holds 1999. As with virtuals, getters are applied by toJSON only when you set toJSON: { getters: true }. Getters do not run in lean() queries unless you use the mongoose-lean-getters plugin, so a lean result shows the raw stored value.

A getter can also be attached to a path after the fact:

JavaScript
productSchema.path('priceCents').get((v) => (v / 100).toFixed(2));

Setters

A setter transforms a value as it is assigned, before casting and validation. The built-in trim, lowercase and uppercase string options are setters. A custom one:

JavaScript
const userSchema = new mongoose.Schema({
  email: { type: String, set: (v) => v.trim().toLowerCase() },
  phone: { type: String, set: (v) => v.replace(/\D/g, '') },
});

Now ' [email protected] ' is stored as '[email protected]' and '(555) 010-4477' as '5550104477'. Normalizing at the setter is much safer than hoping every code path cleans input first.

Node.js Getters and setters on a field (stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Virtual populate

Virtuals have one more power: virtual populate. If another collection points to this one (posts reference a user), you can expose the reverse direction without storing an array of post ids on the user:

JavaScript
userSchema.virtual('posts', {
  ref: 'Post',
  localField: '_id',
  foreignField: 'author',
});

const user = await User.findById(id).populate('posts');

The posts virtual is not stored; it is filled by an extra query when you call populate. It keeps the one-to-many link on the "many" side only, avoiding an ever-growing array. The population chapter returns to this.

Choosing between them

You want Use
A computed read-only value from several fields Virtual with get
A value to be assignable that updates several fields Virtual with get and set
Different representation of one stored field when reading Getter
Normalize input before it is stored Setter
The reverse side of a reference Virtual populate

Common mistakes

  • Using an arrow function, so this is not the document.
  • Querying by a virtual.
  • Forgetting toJSON: { virtuals: true } and wondering why the API response lacks the field.
  • Using a getter that changes the type (toFixed returns a string) and then doing arithmetic on it.
  • Expecting getters to run on lean() results.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Is a virtual stored in the database?

    Virtuals exist only on the document object; MongoDB never stores them.
  2. 2. Why does Person.find({ fullName: 'Ada Lovelace' }) return nothing for a virtual fullName?

    Filters run in MongoDB, which knows only the stored fields.
  3. 3. What must you enable so virtuals appear in res.json(doc)?

    By default toJSON and toObject omit virtuals.
  4. 4. When does a setter run?

    Setters transform input as it is assigned, which makes them good for normalizing.

Summary

  • Virtuals are computed properties that are not stored and cannot be queried; include them in JSON with toJSON: { virtuals: true }.
  • Getters change how a stored value is read; setters change a value as it is assigned.
  • Use a normal function so that this is the document.
  • Virtual populate exposes the reverse side of a reference without storing arrays of ids.

Next: Methods, statics and query helpers