Search code examples
mongodbmongoosemongoose-populate

How does mongoose populate work under the hood


Could somebody tell me how

I have a collection

a {
 b: String
 c: Date
 d: ObjectId --> j
}

j {
 k: String
 l: String
 m: String
}

when I carry out a:

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

in the background is this actually carrying out two queries against the MongoDB in order to return all the items 'j'?

I have no issues getting populate to work, what concerns me is the performance implications of the task.

Thanks


Solution

  • 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);