How does mongoose populate work under the hood How does mongoose populate work under the hood mongoose mongoose

How does mongoose populate work under the hood


Mongoose uses two queries to fulfill the request.

The a collection is queried to get the docs that match the main query, and then the j collection is queried to populate the d field in the docs.

You can see the queries Mongoose is using by enabling debug output:

mongoose.set('debug', true);


Basically the model 'a' is containing an attribute 'd' which is referencing(pointing) towards the model 'j'.

So whenever we use

a.find({ b: 'thing' }).populate('d').exec(etc..)

Then through populate we can individually call properties of 'j' like :

  • d.k
  • d.l
  • d.m

Populate() helps us to call properties of other models.


Adding to @JohnnyHK answer on the performance implications of the task you worried about, I believe no matter what, these queries have to execute sequentially whether we use the mongoose provided populate() method or the one you will implement the server-side, both will have the same time complexity.

This is because in order to populate we need to have the results from the first query, after getting the result uuid will be used to query the document in the other collection.

So I believe it's a waste to make these changes the server-side than to use the mongoose provided method. The performance will remain the same.