NodeJS MongoDB Populate with Mongoose

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

In MongoDB, there are usually various collections with several documents. While working with MongoDB and NodeJS, we may need to link the documents of various collections. For such operations, Mongoose provides a method known as populate. This is similar to a join in relational databases and allows us to consolidate information from various collections into one result. As you can imagine this is extremely useful when querying any type of database. Without further ado we’ll jump straight in and show you a demonstration of how to use the populate function in Mongoose with MongoDB and NodeJS.

Populate with Mongoose

  1. Creating schema

We will have two schemas – EmployeeSchema and LocationsSchema

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const EmployeeSchema = new mongoose.Schema({
  employeeName: String,
  locations: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Location"
    }
  ]
});

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

const Employee = mongoose.model("Employee", EmployeeSchema, "employees");
const Location = mongoose.model("Location", LocationsSchema, "locations");

module.exports = {
  Employee,
  Location
};

Pay attention to the EmployeeSchema. There are two fields – employeeName and locations. The locations field is what we will populate. It has the type – mongoose.schema.Types.ObjectId and ref mean the reference to the LocationsSchema. (The LocationsSchema is exported as Location). The second schema – LocationsSchema has one field – location.

  1. Creating Employee and Location collections

Let’s see what the location document will look like:

1
2
3
4
5
6
7
8
9
10
11
12
{
    _id : 5d715243c452f78e335d2d8c,
    location : "New York"


},
{
    _id : 5d71524ec452f78e335d2d8d,
    location : "Texas"


}

Now pay attention to the document in the Employee collection:

1
2
3
4
5
6
7
8
9
{
    _id : 5d71522dc452f78e335d2d8b,
    employeeName: "John",
    locations : [
    "5d715243c452f78e335d2d8c",
    "5d71524ec452f78e335d2d8d"
    ]

}

The first field is the name of the employee. The second field is an array of strings. Every string has an id of a document from the Location collection (LocationsSchema), because we gave reference to it earlier.

We have not used the populate method yet.

  1. Implementing .Populate()

Let’s have a look at the function.

1
2
3
4
5
6
7
function getEmployeesWithLocations(employeeName) {
  return Employee.findOne({ employeeName: employeeName })
    .populate("locations")
    .exec((err, locations) => {
      console.log(locations);
    });
}

The populate method needs to be attached to 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 employees. The console will print the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  _id: 5d71522dc452f78e335d2d8b,
  employeeName: 'John',
  locations:
    [
      {
        _id: 5d715243c452f78e335d2d8c,
        location: "New York"
      },{
        _id: 5d71524ec452f78e335d2d8d,
        location: "Texas"
      }
    ]
  }

Observe the output. The values from the Location collection is populated to the Employee collection’s document.

Conclusion

The populate function populates the data from one document of a collection to one document of another collection. It can be a bit tricky but as we mentioned before extremely common and extremely useful. All we need is to create schemas correctly and use the populate method properly. This is an essential command if you’re working with MongoDB through Mongoose. We hope the demo here was able to help you on your way to creating something amazing.

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.