What is Population in Mongoose?

Population or Query Population in mongoose is a process of automatically replacing paths with other documents from other collections in a single document, multiple documents, objects, multiple objects. That’s the official definition of the population by a mongoose. But, most of us would understand this one: “Population is simply a process of replacing objectID in a mongoose document with its data from its collection in the database. Population can only be done on along with mongoose queries or mongoose objects returned by mongoose queries”.

Populate() method

The process of population is carried out by populate method in mongoose. Now how does it work? Let’s look at an example:

ExampleDB.findOne({ title: 'Casino Royale' }).populate('author')

In the above line of code findOne() method will find a document in ExampleDB that has the title Casino Royale and then in that document if there is any id with the key author it will replace that id with the data of the author from Author collection and return the document with author data in it.

One thing that confuses beginners: “The name of the key that you are populating doesn’t have to match with the name of the collection of that id“. For Example,

ExampleDB.findOne({title: 'Collection author').populate('authorID')

The above code will return the same result as before, why? Because now we have changed the key author in our model to authorID for ExampleDB collection but when we populate authorID MongoDB searches its entire record for that key and populates the data of that key from its collection into this Object and then returns the result.

If you want to nest population i.e. you want to populate author inside ExampleDB and then comments inside author then this is how you do it:

ExampleDB
.findOne({title: "Nested Population"})
.populate({
   path: "author",
   populate: {
      path: "comments"
   }
})

These are the most widely used population techniques in mongoose if you wanna dive deeper into the population then read the documentation here. If the code doesn’t work or you face any problem feel free to comment I will reach out to you or just drop me an email.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.