Join operator of Node.js Mongoose
.populate() method Aka join operation of mongoose. This is similar to a join in relational databases and allows us to consolidate information from various collections into one result.
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 is a Mongoose method that you can use to essentially link documents across collections. This allows you to have a schema for each of them, and generally keep things all nice and tidy.
In EmployeeSchema There are two fields — employeeName and locations. The locations field is what we will populate. It has the type of 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:
Now pay attention to the document in the Employee collection:
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.
2. Implementing.Populate() Let’s have a look at the function.
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.
Observe the output. The values from the Location collection is populated to the Employee collection’s document.
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.
Reference: Data Pilot