Mongoose Populate Virtuals
Last Updated :
28 Mar, 2025
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 explore Mongoose Populate Virtuals, a powerful feature that allows us to populate virtual properties in Mongoose models.
How to Use Mongoose Populate Virtuals?
The mongoose populate method can be used to fetch referenced documents and populate them in the query result. Virtuals are properties that are not persisted in the database but are computed on the fly by the model. To populate a virtual property, you can use the populate() method with an options object that has a path property that specifies the name of the virtual property to populate.
The path property should be set to the name of the virtual property prefixed with an underscore. Mongoose's populate()
method allows you to populate a virtual property just as easily as you would populate a regular document reference field. However, populating a virtual field requires a slightly different setup. The virtual field is populated by specifying its path with an underscore (_
) prefix.
Syntax:
Model.find(query)
.populate(path, select, model, match, options)
.exec(callback);
Parameters:
- path (required) - The path to the field to populate. This can be a string or an object that specifies the path and any additional options.
- select (optional) - The fields to include or exclude from the populated document. This can be a string or an object that specifies the fields to include or exclude.
- model (optional) - The name of the model to use for populating the field, if different from the default model for the reference.
- match (optional) - Additional conditions to match when populating the field. This can be an object that specifies the conditions to match.
- options (optional) - Additional options for the query, such as limit or sort. This can be an object that specifies the query options.
Installation of mongoose module
To use Mongoose and start populating virtuals, you need to install the Mongoose package in your Node.js project. Here's how we can install Mongoose:
Step 1: We can install this package by using this command.
npm install mongoose
Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.
npm version mongoose
Step 3: After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.
node index.js
Project Structure: The project structure will look like this:
Example 1: Populating a Virtual Property for a Full Name
In this example the book.save() method takes a callback function that is executed after the book is saved to the database. Inside the callback, we call Book.findById and use the populate() method to fetch the book's author with the fullName virtual field. This code should log the book title and author's full name to the console without any errors.
Filename: Index.js
const mongoose = require("mongoose");
mongoose.set("strictQuery", true);
mongoose.connect(
"mongodb://localhost:27017/geeksforgeeks", {
useNewUrlParser: true,
});
// Define the User schema
const userSchema = new mongoose.Schema({
first: String,
last: String,
});
// Define a virtual field to retrieve
// the user's full name
userSchema.virtual("fullName").get(function () {
return `${this.first} ${this.last}`;
});
// Define the Book schema
const bookSchema = new mongoose.Schema({
title: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
});
// Define the User and Book models
const User = mongoose.model("User", userSchema);
const Book = mongoose.model("Book", bookSchema);
// Create a new user and save it to the database
const user = new User({ first: "John", last: "Doe" });
user.save();
// Create a new book and associate it with the user
const book = new Book({
title: "My Book Title",
author: user._id,
});
book.save((err) => {
if (err) console.error(err);
// Use the populate() method to fetch
// the book's author with the
// fullName virtual field
Book.findById(book._id)
.populate({
path: "author",
select: "first last",
})
.exec((err, book) => {
if (err) console.error(err);
console.log(book);
console.log(`Title: ${book.title}`);
console.log(`Author: ${book.author.fullName}`);
});
});
Steps to run:
Make sure you have installed the mongoose module using the following command:
npm install mongoose
Run the index.js file using the below command:
node index.js
Output:
Explanation:
In this example, we define a virtual property fullName
in the User
schema. When the Book
document is populated, we use the populate()
method to fetch the author
field, which references the User
model. By using the virtual field fullName
, we are able to dynamically compute the full name without storing it in the database.
Example 2: Populating a Virtual Field with an Array of Posts
In this example, we create a new User document with an empty posts array and save it to the database. We then create a new Post document and save it to the database, and add the Post document id to the User's posts array. We save the User again, and then fetch it from the database, populating its posts field with the actual Post documents. The resulting document is logged to the console.
Filename: Index.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
mongoose.set("strictQuery", true);
const PostSchema = new Schema({
title: String,
content: String,
author: {
type: Schema.Types.ObjectId,
ref: "User",
},
});
// Define the User schema
const UserSchema = new Schema({
name: String,
email: String,
posts: [
{
type: Schema.Types.ObjectId,
ref: "Post",
},
],
});
// Define the models
const User = mongoose.model("User", UserSchema);
const Post = mongoose.model("Post", PostSchema);
mongoose
.connect("mongodb://localhost:27017/geeksforgeeks")
.then(() => {
console.log("Connected to Database");
// Create a new user
const user = new User({
name: "Bob",
email: "[email protected]",
posts: [],
});
// Save the user to the database
user.save((err, user) => {
if (err) {
console.log(err);
} else {
console.log("User saved:", user);
// Create a new post
const post = new Post({
title: "New Post",
content: "Content for new post",
author: user._id,
});
// Save the post to the database
post.save((err, post) => {
if (err) {
console.log(err);
} else {
console.log("Post saved:", post);
// Add the post to the user's posts array
user.posts.push(post._id);
// Save the user again
user.save((err, user) => {
if (err) {
console.log(err);
} else {
console.log("User with new post:", user);
// Populate the user's posts array with
// actual post documents
User.findById(user._id)
.populate("posts")
.exec((err, user) => {
if (err) {
console.log(err);
} else {
console.log(
"User with populated posts:",
user
);
}
mongoose.disconnect();
});
}
});
}
});
}
});
})
.catch((err) => {
console.error("Error connecting to the database", err);
});
Steps to run:
Run the following command:
node index.js
Output:
Explanation: In this example, we created a virtual field postsArray
in the User
schema to populate all posts related to a specific user. The virtual field is populated using the populate()
method, which retrieves the post documents and displays them within the postsArray
field.
Conclusion
Mongoose Populate Virtuals is a powerful feature that allows you to populate dynamic, computed properties without storing them in the database. By using the get()
and set()
methods to create virtual fields, and then using populate()
to dynamically retrieve data, you can simplify data management and retrieval in your Mongoose models. Populating virtual fields is especially useful for cases where you want to enrich your data with computed or related information without directly modifying your database schema.
Similar Reads
Mongoose Tutorial
Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js that simplifies database interactions by providing a schema-based solution to model application data. It is widely used to build scalable, structured, and efficient database-driven applications.Built on MongoDB for seam
6 min read
Mongoose Schemas
Mongoose Schemas Creating a Model
Mongoose is one of the most popular Object Data Modeling (ODM) libraries for MongoDB, providing schema-based solutions to model our application's data. This allows us to define the structure of documents within a MongoDB collection, including validation, typecasting, and other powerful features that
5 min read
Mongoose Schemas and Indexes
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB in a Node.js environment. It provides a straightforward way to interact with MongoDB, including features like schema definition, model creation, and database query handling. One key feature of Mongoose is its ability to create and
5 min read
Mongoose Schemas Instance methods
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB, designed to work in a Node.js environment. One of the key features of Mongoose is its ability to define instance methods on schema objects, which allow you to perform operations on individual documents. This guide will explore Mo
5 min read
Mongoose Schemas Ids
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn't allow us to save or create a
2 min read
Mongoose Schemas Virtuals
Virtuals are a powerful feature in Mongoose that allow us to add attributes to documents without actually storing them in the database. These properties can be dynamically calculated based on other fields, making it easier to manage and manipulate your data. In this comprehensive article, weâll dive
6 min read
Mongoose Schemas Aliases
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability. Creating node application And Installing Mongoose: Step 1: Create a
2 min read
Mongoose Schemas With ES6 Classes
Mongoose is a MongoDB object modeling and handling for a node.js environment. To load Mongoose schema from an ES6 Class, we can use a loadClass() method which is provided by Mongoose Schema itself. By using loadClass() method: ES6 class methods will become Mongoose methodsES6 class statics will bec
2 min read
Mongoose Schemas Query Helpers
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schema Query Helpers are like instance methods for Mongoose queries. These query helpers can be used to filter out mongoose query results or perform additional operations on the existing result. Creating node appl
3 min read
Mongoose Documents
Mongoose Documents
Mongoose is a powerful Object Data Modeling (ODM) library for MongoDB and Node.js, making it easier to interact with MongoDB databases. It provides a structured way to handle data, perform validation, and manage documents in MongoDB with ease. In this article, we will explain Mongoose Documents, how
5 min read
Mongoose Documents vs Models
Mongoose, a popular Node library, is widely used for interacting with MongoDB, a NoSQL database. Mongoose simplifies the process of working with MongoDB by providing an object data modeling (ODM) framework. In the Mongoose ecosystem, two key concepts are Documents and Models. In this article, we'll
4 min read
Mongoose Documents Updating Using save()
An important aspect of a mongoose model is to save the document explicitly when changes have been made to it. This is done using the save() method. In this article, we will see its uses and see the things we should keep in mind while saving our document.We will take the help of an example to underst
5 min read
Mongoose Queries
Mongoose Queries
Mongoose is a powerful object modeling tool for MongoDB and Node.js. It provides a schema-based solution to model your data, simplifying interactions with MongoDB databases. Mongoose queries are essential for performing CRUD (Create, Read, Update, Delete) operations, making them indispensable for an
7 min read
Mongoose deleteMany() Function
The deleteMany() function is employed to remove all documents meeting specified conditions from a collection. Unlike the remove() function, deleteMany() deletes all matching documents without considering the single option. This method is essential for Node.js developers working with Mongoose, as it
4 min read
Mongoose Queries Model.replaceOne() Function
The Queries Model.replaceOne() function of the Mongoose API is used to replace an existing document with the given document. It replaces only the first document that is returned in the filter. Syntax: Model.replaceOne( filter, doc, options, callback ) Parameters: It accepts the following 4 parameter
3 min read
Find() Method in Mongoose
The Mongoose find() method is one of the most widely used methods for querying MongoDB collections in Node.js. It provides a flexible and powerful way to fetch data from your MongoDB database. In this article, we will explore the find() method in detail, its syntax, parameters, and how to implement
5 min read
FindById Method in Mongoose
The findById() method in Mongoose is one of the most commonly used methods for retrieving a document by its unique identifier (_id) in a MongoDB collection. This article will cover everything we need to know about how to use the findById() method, including syntax, examples, installation, and troubl
4 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
Mongoose findByIdAndRemove() Function
MongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific i
2 min read
Mongoose QueriesModel.findByIdAndDelete() Method
The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field. Installation of Mongoose Module: Step 1. You can visit the link to Install the mo
4 min read
FindOne() Method in Mongoose
The findOne() method in Mongoose is one of the most commonly used functions for querying data from a MongoDB database. It provides a simple and efficient way to retrieve a single document that matches a specified query condition. This article will explore how to use the findOne() method, explain its
5 min read
Mongoose findOneAndDelete() Function
The findOneAndDelete() function in Mongoose is an efficient and commonly used method to find a document based on a specified filter and delete it from a MongoDB collection. This method simplifies the process of removing documents and is a key tool for developers working with Node.js and MongoDB. In
5 min read
Mongoose | findOneAndRemove() Function
The findOneAndRemove() function is used to find the element according to the condition and then remove the first matched element. Installation of mongoose module:You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongooseAfter installin
2 min read
Mongoose | findOneAndReplace() Function
When working with MongoDB in Node.js, Mongoose is an essential tool for schema-based modeling and database operations. One of the most powerful and frequently used functions in Mongoose is findOneAndReplace(). This function helps in finding a document and replacing it with a new one. But how exactly
5 min read
Mongoose Queries Model.findOneAndUpdate() Function
The Queries Model.findOneAndUpdate() function of the Mongoose API is used to find and update an existing document with the information mentioned in the "update" object. It finds and updates only the first document that is returned in the filter. Syntax: Model.findOneAndUpdate(conditions, update, opt
3 min read
Mongoose Document Model.replaceOne() API
The Model.replaceOne() method of the Mongoose API is used to replace any one document in a collection. This method works the same as the update method but it replaces MongoDB's existing document with the given document with any atomic operator i.e $set. Syntax: Model.replaceOne() Parameters: Â The Mo
3 min read
updateMany() Method in Mongoose
In Mongoose, the updateMany() method is a powerful tool for performing bulk updates in MongoDB. It updates multiple documents that match a specified condition, applying the changes to all the matched documents in a single operation. Unlike updateOne(), which updates only the first matching document,
4 min read
Mongoose Queries Model.updateOne() Function
The Queries Model.updateOne() function of the Mongoose API is used to update an existing document with the information mentioned in the "update" object. It updates only the first document that is returned in the filter. Syntax: Model.updateOne(filter, update, options, callback ) Parameters: It accep
3 min read