How to populate virtuals to a mongoose model using Node.js ?
In Mongoose, the virtual is the property that is not stored in the database, they only exist logically, and you cannot query directly on the basis of this property. To know more about virtual refers to this article Mongoose Virtuals.
In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
Mongoose also supports a population of virtual properties during their creation. Whenever we want our virtual property to refer to a model of any other collection we have to populate it so that it can contain the document(s) of the other collection.
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: Now you can import the mongoose module in your file using:
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.
- Create a folder and add the file main.js.
- 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.
Mongoose will populate those documents from the model given in ref, whose foreignField value will match with the localField value of the current collection.
Example: Now we will see how to populate virtuals to a mongoose model using Node.js.
Run main.js using the command:
Explanation: Here we are finding User 1 by _id field and then creating a post whose postedBy field value will be the User 1 _id field value (hence the post is created by User 1). Whenever a post will be created, a virtual property ‘user’ will be created for the post which would be populated with the document of the User model whose _id field value matches with the postedBy value of the post.
Database: After creating a post with a populated virtual property user, we can see Post 1 in posts collection of our database. But here we cannot see the property user in the database because it’s a virtual property, and it doesn’t get stored in the database.