How to Populate Virtuals to a Mongoose Model using Node.js ?
Last Updated :
01 Apr, 2025
Mongoose virtuals are properties that are not stored in the database but are computed from other document fields. They exist logically within a Mongoose document and allow us to handle derived data, such as full names, formatted dates, or aggregated values, without physically storing them in the database.
While virtuals are not queryable directly, you can populate them with data from other collections using the populate()
method. This allows us to create dynamic relationships between documents, enhancing the flexibility and efficiency of your application.
What is Populating Virtuals in Mongoose?
Populating virtuals in Mongoose refers to the process of dynamically fetching and attaching data from one collection to a virtual property in another collection. When you populate a virtual field, Mongoose replaces the virtual property with actual data from a referenced collection, based on a defined relationship
For example, we might have a Post
schema where the author
field references a User
document. Instead of storing the author's full name in the Post
collection, you can create a virtual field that pulls in the author’s data when needed.
How to Set Up Virtual Populate in Mongoose
To use virtual populate in Mongoose, we need to follow these steps
- Define a virtual field in your schema: This field will compute data dynamically based on other fields or related documents.
- Populate the virtual field: Use the
populate()
method to load data from another collection into the virtual field.
Below is a step-by-step implementation guide using Node.js and Mongoose.
Installation of Mongoose Module
Step 1: You can visit the link Install mongoose to install the mongoose module. You can install this package by using this command.
npm install mongoose
Step 2: After installation, we can import Mongoose into your Node.js files:
const mongoose = require('mongoose');
Database: We have two collections users and posts in our database GFG.Â
- users: The users collection has two users User1 and User2.
- posts: The posts collection is empty.
Initially users and posts collection in databaseImplementation:
1. Create a folder and add the file main.js.
2. For populating virtual, we have to specify three necessary options:
- ref: It contains the name of the model from which we want to populate the document.
- localField: It is any field of the current collection.
- foreignField: It is any field of the collection from which we want to populate the document.
Example: Populating Virtual Fields in Mongoose
In this example, we'll create two collections: users
and posts
. We will define a virtual field in the Post
schema that will refer to the User
collection and fetch the author's details when populating.
Filename: main.js
// Requiring module
const mongoose = require('mongoose');
// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
// User Schema
const userSchema = new mongoose.Schema({
username: String,
email: String
})
// Post Schema
const postSchema = new mongoose.Schema({
title: String,
postedBy: mongoose.Schema.Types.ObjectId
})
// Creating and populating virtual property 'user' in postSchema
// will populate the documents from user collection if
// their '_id' matches with the 'postedBy' of the post
postSchema.virtual('user', {
ref: 'User',
localField: 'postedBy', // Of post collection
foreignField: '_id', // Of user collection
justOne: true
})
// Creating user and post models
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
// Function to create a post by the user
const createPost = async (next) => {
const user = await User.findOne({ _id: '60acfa48e82a52560c32ec0a' });
const newPost = new Post({
title: 'Post 1',
postedBy: user._id
})
const postSaved = await newPost.save();
console.log("post created");
// The findPost will be called after the post is created
next();
}
// Function to find the post and show the virtual property
const findPost = async () => {
const post = await Post.findOne().populate('user');
console.log(post.user);
}
// Creating the post then showing the virtual property on console
createPost(findPost);
Run main.js using the command:
node main.js
Output: Â
Output after executing main.jsExplanation:
- Virtual Field Definition: In the
Post
schema, the user
virtual field is defined using the virtual()
method. This virtual field references the User
model, using the postedBy
field from the Post
collection and matching it to the _id
field in the User
collection.
- Populate: The
populate()
method is called on the Post
model to fetch the associated user data. The user
virtual field will be populated with the user document whose _id
matches the postedBy
field of the post.
Posts collection after creating the post with populated virtualBy using virtuals and populate, we avoid redundant data storage (e.g., storing the author's details directly in the Post
collection) while still being able to efficiently access the related data.
Why Use Mongoose Populate Virtuals?
- Data Normalization: By storing references to other documents rather than duplicating data, you avoid redundancy and maintain consistency.
- Simplified Data Access: Using populate with virtuals allows you to seamlessly include related documents in your queries without manually querying the related collections.
- Improved Performance: Virtual populate ensures that you only load related data when necessary, which can help with performance optimization.
Conclusion
Populating virtual fields in Mongoose is a powerful feature that allows you to enrich your MongoDB documents with dynamically computed properties and referenced data from other collections. By defining virtual fields and using the populate()
method, you can easily manage relationships between models without duplicating data in the database. This article covered how to define and populate virtual fields in Mongoose, making it easier for developers to manage complex data relationships in a clean and efficient manner.
Similar Reads
How to Use MongoDB and Mongoose with Node.js ?
MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
How to Connect Node.js To MongoDB Atlas Using Mongoose?
MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria
6 min read
Mongoose Populate Virtuals
Mongoose Populate Virtuals refers to the ability to use the populate() method to populate virtual fields in your Mongoose models. Virtual fields, unlike regular fields, do not get stored in the database. Instead, they are computed on the fly based on other document data. In this article, we will exp
7 min read
How to Make Mongoose Multiple Collections using Node.js ?
Creating multiple collections in MongoDB using Mongoose with Node.js involves defining different Mongoose schemas and models for each collection. Mongoose allows for a straightforward and schema-based approach to managing MongoDB collections. Hereâs a step-by-step guide on how to create and manage m
4 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to Perform Data Migration in MongoDB using Node.js?
In this article, we migrate existing data from the sourced database (MongoDB) to the destination database (MongoDB) using Node.js. To perform the whole operation, we will first insert documents into the sourced database and then migrate to the destination. Approach to Perform Data Migration in Mongo
3 min read
How to Post Data in MongoDB Using NodeJS?
In this tutorial, we will go through the process of creating a simple Node.js application that allows us to post data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple
5 min read
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
CRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
8 min read
How to work Mongojs module in Node.js ?
Mongojs module is a built-in module in node.js that facilitates the usage of MongoDB with Node.js. It offers almost all the functionality that is provided by the official API of MongoDB and is used extensively by developers across the globe. Â Follow the steps mentioned below to install mongojs modu
3 min read
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read