• Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact

Virtual Attributes in mongoose

Aug 16th, 2019

Alex Quasar


Attributes that are convenient to have around but are not persisted to the mongo database. These are usually fields that we can get from the other values in our database. For example, if we store first name and last name, we don't really need another field to store the full name. The users' full name can be calculated and stored as a virtual attribute.

Let's get started with virtual attributes and calculate the price that the customer will pay for a tour:

We have the price and price discount stored, so we can write the following virtual method in our Tour model:

TourSchema.virtual('customerPrice').get( function() {
  return (this.price - priceDiscount) *1.07;
} ) 

In order for the virtual attributes to show, we need to tell mongoose this by passing it in the options field right after the Schema is defined.

  toObject: { virtuals: true },
  toJSON: { virtuals: true }

It is good practice to store business logic inside the models you create rather than defining them later on in the request and response API. This keeps the logic, close to the source of the model and keeps the APIs `slim`.