Open In App

Mongoose Populate() Method

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Need of Population: Whenever in the schema of one collection we provide a reference (in any field) to a document from any other collection, we need a populate() method to fill the field with that document.

Example: In the following example, we have one userSchema and another postSchema, in the postSchema we have one field postedBy which references a document from the User model.

const userSchema = new mongoose.Schema({
username: String,
email: String
})
const postSchema = new mongoose.Schema({
title: String,
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
})
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
module.exports = {
Source, Destination, User, Post
}

Steps to Install mongoose:

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: Initially we have two collections users and posts in our database GFG. And each collection contains a single document.

Initially users and posts collection in the database

Example 1: We will perform the query to find all the posts without using populate() method. Create a folder and add the file main.js which is shown below:

Javascript




// main.js
 
// Requiring module
const mongoose = require('mongoose');
 
// Connecting to database
mongoose.connect('mongodb://localhost:27017/GFG',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false
    });
 
// Creating Schemas
const userSchema = new mongoose.Schema({
    username: String,
    email: String
})
 
const postSchema = new mongoose.Schema({
    title: String,
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }
})
 
// Creating models from userSchema and postSchema
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
 
// Query to find and show all the posts
Post.find()
    .then(p => console.log(p))
    .catch(error => console.log(error));


Steps to run main.js using the below command: 

node main.js

Output: In the output, we can see that we get only ObjectId (_id field of user document) in postedBy field, and not the whole document.

Output in the console after executing main.js

Example 2: We will perform the query to find all the posts using populate() method. To overcome the above problem, populate() method is used to replace the user ObjectId field with the whole document consisting of all the user data. For this we only have to replace the query part in the above code in main.js file with:

Post.find()
.populate("postedBy")
.then(p=>console.log(p))
.catch(error=>console.log(error));

Note: In the argument of the populate() method we pass the field we want to populate with the user data.

Output: After using the populate method, we can see that in the output we can get all the user data inside the postedBy field of posts.

Output after using the populate method in the code



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads