How to Use Mongoose Populate

Introduction

In real-time, there are many collections in a MongoDB database. While working with an application, we may need to link these collections. It is a bit complex task, but mongoose provides the populate() method that helps us with this. In this article, we will discuss how to use mongoose populate. Let’s jump in!

Schemas

To understand the populate() method, we need to create two schemas. The two schemas we are going to create are – detailSchema and locationsSchema.

const detailSchema = new mongoose.Schema({
  name: String,
  age: Number,
  locations: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "location"
    }
  ]
});

const locationsSchema = new mongoose.Schema({
  location: String
});

const details = mongoose.model("detail", detailSchema, "details");
const location = mongoose.model("location", locationsSchema, "locations");

module.exports = {
  details,
  location
};

This is how our model looks. Observe attention to the detailSchema. It contains three fields – name, age, and locations. We will populate the locations field. The type of location field is mongoose.schema.Types.ObjectId. The ref denotes the reference. The reference is to the locationsSchema.

Mongoose Collections

The next step is to understand the collections. The locations collections look like this.

{
    _id : 5d715243c252f08e235d1d9c,
    location : "Chicago"


},
{
    _id : 5d81514ec552f89e336d2d8d,
    location : "Detroit"


}

Observe the details collection.

{
    _id : 5d73622dc452f69e446d2d9b,
    name: "Sam",
    age: 21,
    locations : [
    "5d715243c252f08e235d1d9c",
    "5d81514ec552f89e336d2d8d"
    ]

}

Check the locations field. It is an array of strings. When we look carefully, these strings are nothing, but the values of the _id field of the documents of the locations collection. This is why we gave a reference at the time of defining the schema.

Now, we can use the populate() method.

Mongoose populate() method

Have a look at the following function.

function getDetailsAndLocations(name) {
  return details
    .findOne({ name: "name" })
    .populate("locations")
    .exec((err, locations) => {
      console.log(locations);
    });
}

We need to attach the populate() method with a query. That is why we used the findOne method. The findOne method will return a document according to the value passed to it. Then we used the populate method and passed the locations in it. This will populate the locations to the details. The following will be printed in the console.

{
  _id: 5d73622dc452f69e446d2d9b,
  name: “Sam”,
  age:21
  locations:
    [
      {
        _id: 5d715243c252f08e235d1d9c,
        location: "Chicago"
      },{
        _id: 5d81514ec552f89e336d2d8d,
        location: "Detroit"
      }
    ]
  }

Check the output. The values from the locations collection are populated to the details collection’s document.

Conclusion

The populate() method populates the data from one document of a collection to a document of another collection. This method is complicated and it takes time and practice to understand it. All we need is to create schemas correctly and use the populate method properly.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.