Mongoose Virtuals

In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents.

Your First Virtual

Suppose you have a User model. Every user has an email, but you also want the email’s domain. For example, the domain portion of ‘test@gmail.com’ is ‘gmail.com’.

Below is one way to implement the domain property using a virtual. You define virtuals on a schema using the Schema#virtual() function.

  1. const userSchema = mongoose.Schema({
  2. email: String
  3. });
  4. // Create a virtual property `domain` that's computed from `email`.
  5. userSchema.virtual('domain').get(function() {
  6. return this.email.slice(this.email.indexOf('@') + 1);
  7. });
  8. const User = mongoose.model('User', userSchema);
  9. let doc = await User.create({ email: 'test@gmail.com' });
  10. // `domain` is now a property on User documents.
  11. doc.domain; // 'gmail.com'

The Schema#virtual() function returns a VirtualType object. Unlike normal document properties, virtuals do not have any underlying value and Mongoose does not do any type coercion on virtuals. However, virtuals do have getters and setters, which make them ideal for computed properties, like the domain example above.

Virtual Setters

You can also use virtuals to set multiple properties at once as an alternative to custom setters on normal properties. For example, suppose you have two string properties: firstName and lastName. You can create a virtual property fullName that lets you set both of these properties at once. The key detail is that, in virtual getters and setters, this refers to the document the virtual is attached to.

  1. const userSchema = mongoose.Schema({
  2. firstName: String,
  3. lastName: String
  4. });
  5. // Create a virtual property `fullName` with a getter and setter.
  6. userSchema.virtual('fullName').
  7. get(function() { return `${this.firstName} ${this.lastName}`; }).
  8. set(function(v) {
  9. // `v` is the value being set, so use the value to set
  10. // `firstName` and `lastName`.
  11. const firstName = v.substring(0, v.indexOf(' '));
  12. const lastName = v.substring(v.indexOf(' ') + 1);
  13. this.set({ firstName, lastName });
  14. });
  15. const User = mongoose.model('User', userSchema);
  16. const doc = new User();
  17. // Vanilla JavaScript assignment triggers the setter
  18. doc.fullName = 'Jean-Luc Picard';
  19. doc.fullName; // 'Jean-Luc Picard'
  20. doc.firstName; // 'Jean-Luc'
  21. doc.lastName; // 'Picard'

Virtuals in JSON

By default, Mongoose does not include virtuals when you convert a document to JSON. For example, if you pass a document to Express’ res.json() function, virtuals will not be included by default.

To include virtuals in res.json(), you need to set the toJSON schema option to { virtuals: true }.

  1. const opts = { toJSON: { virtuals: true } };
  2. const userSchema = mongoose.Schema({
  3. _id: Number,
  4. email: String
  5. }, opts);
  6. // Create a virtual property `domain` that's computed from `email`.
  7. userSchema.virtual('domain').get(function() {
  8. return this.email.slice(this.email.indexOf('@') + 1);
  9. });
  10. const User = mongoose.model('User', userSchema);
  11. const doc = new User({ _id: 1, email: 'test@gmail.com' });
  12. doc.toJSON().domain; // 'gmail.com'
  13. // {"_id":1,"email":"test@gmail.com","domain":"gmail.com","id":"1"}
  14. JSON.stringify(doc);
  15. // To skip applying virtuals, pass `virtuals: false` to `toJSON()`
  16. doc.toJSON({ virtuals: false }).domain; // undefined

Virtuals in console.log()

By default, Mongoose does not include virtuals in console.log() output. To include virtuals in console.log(), you need to set the toObject schema option to { virtuals: true }, or use toObject() before printing the object.

  1. console.log(doc.toObject({ virtuals: true }));

Virtuals with Lean

Virtuals are properties on Mongoose documents. If you use the lean option, that means your queries return POJOs rather than full Mongoose documents. That means no virtuals if you use lean().

  1. const fullDoc = await User.findOne();
  2. fullDoc.domain; // 'gmail.com'
  3. const leanDoc = await User.findOne().lean();
  4. leanDoc.domain; // undefined

If you use lean() for performance, but still need virtuals, Mongoose has an officially supported mongoose-lean-virtuals plugin that decorates lean documents with virtuals.

Limitations

Mongoose virtuals are not stored in MongoDB, which means you can’t query based on Mongoose virtuals.

  1. // Will **not** find any results, because `domain` is not stored in
  2. // MongoDB.
  3. mongoose.set('debug', true)
  4. const doc = await User.findOne({ domain: 'gmail.com' }, null, { strictQuery: false });
  5. doc; // undefined

If you want to query by a computed property, you should set the property using a custom setter or pre save middleware.

Populate

Mongoose also supports populating virtuals. A populated virtual contains documents from another collection. To define a populated virtual, you need to specify:

  • The ref option, which tells Mongoose which model to populate documents from.
  • The localField and foreignField options. Mongoose will populate documents from the model in ref whose foreignField matches this document’s localField.
  1. const userSchema = mongoose.Schema({ _id: Number, email: String });
  2. const blogPostSchema = mongoose.Schema({
  3. title: String,
  4. authorId: Number
  5. });
  6. // When you `populate()` the `author` virtual, Mongoose will find the
  7. // first document in the User model whose `_id` matches this document's
  8. // `authorId` property.
  9. blogPostSchema.virtual('author', {
  10. ref: 'User',
  11. localField: 'authorId',
  12. foreignField: '_id',
  13. justOne: true
  14. });
  15. const User = mongoose.model('User', userSchema);
  16. const BlogPost = mongoose.model('BlogPost', blogPostSchema);
  17. await BlogPost.create({ title: 'Introduction to Mongoose', authorId: 1 });
  18. await User.create({ _id: 1, email: 'test@gmail.com' });
  19. const doc = await BlogPost.findOne().populate('author');
  20. doc.author.email; // 'test@gmail.com'

Further Reading