DEV Community

Cover image for MongoDB : Understand a Concept of Populate (Bite-size article)
koshirok096
koshirok096

Posted on

MongoDB : Understand a Concept of Populate (Bite-size article)

Intro

Recently I've been working on several MERN Stack projects and I've frequently encountered challenges in grasping the concept of MongoDB's Populate. This experience inspired me to consider writing an article to shed light on the topic.

The concept itself seems simple (maybe), but for people like me, or someone who are new to learning it (or etc), understanding and applying MongoDB's Populate can be quite perplexing in real-world scenarios.

In this article, I will focus on only the basic concept and summarize it briefly.

I hope this article will help others in similar situations!

Understand Basic Concept

MongoDB's Populate method is a functionality designed for connecting related data across various collections stored within a MongoDB database.

Specifically, it is particularly useful to join collections in same database (This concept is somewhat akin to performing table joins in a relational database system).

With the Populate method, you can retrieve information about related documents in a single query.

Image description

Tip: Populate in SQL?

It is very common to pass information from different collections to another to connect them, in many of web development projects. As mentioned, MongoDB can do it using Populate method.

But in SQL databases (relational database system), there is no specific method called Populate. Instead of Populate, there are several ways for combining related data in SQL, such as Join, Subquery, etc.

While MongoDB is a NoSQL DB, SQL, which is SQL-based, naturally has different data handling methods, names, and concepts.

In this article, I will not delve into the differences between NoSQL and SQL in depth, but please do your own research if you are interested in.

Case Study

The following is a basic usage and overview of the Populate method, with code examples.

const mongoose = require('mongoose');

// author model

const authorSchema = new mongoose.Schema({
  name: String,
  books: {
    type: mongoose.Schema.Types.ObjectId, // here is type
    ref: 'Book' // 'Book' is the name of the associated collection
  },
});

// book model

const bookSchema = new mongoose.Schema({
  title: String,
  author: {
    type: mongoose.Schema.Types.ObjectId, // here is type
    ref: 'Author'
  }
});

const Author = mongoose.model('Author', authorSchema);
const Book = mongoose.model('Book', bookSchema);

Enter fullscreen mode Exit fullscreen mode

This code is about DB's Model using Mongoose.

In order to use Populate, a relationship must be set between collections in the MongoDB data model. In this example, there are two collections and the documents in one collection contain references to documents in the other collection.

In this above example code, there are two collections - Author and Book. And each document has a reference to the other collection.

Let's chack the next example.

// retrieving a book by an author with a specific author ID
const authorId = "Author's ObjectId"; // Replace with actual author ID

Author.findById(authorId)
  .populate('books') // 'books' is a field name defined in authorSchema
  .exec((err, author) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log('Author name is: ', author.name);
    console.log("Author's book is: ", author.books); // Author's book has information on related Book documents
  });
Enter fullscreen mode Exit fullscreen mode

This example code combines Author and Book related information to retrieve information about books related to a specific author.

This example uses a specific author ID to find authors in the Author collection and uses the populate method to combine the books fields. This ensures that the author's name and associated book information are retrieved in a single query.

Note: The author's ObjectId in the code must be replaced with the MongoDB document ID of the actual author.

Image description

Outro

Since this article focused on the basic concept, I think the information presented in this article was relatively simple and short. However, real-world projects often involve greater complexity I believe.

To be honest, I am not particularly good at like this kind of DB and Backend programming, but I'm eager to learn a bit every day to get better.

I don't know about your situation, but let's give our best efforts for each other!

Top comments (0)