Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 688
David Avatar asked Feb 13 '15 16:02

David


People also ask

How does populate work in Mongoose?

Mongoose Populate() Method In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

What does .populate do in JavaScript?

populate() Modify a query instance so that, when executed, it will populate child records for the specified collection, optionally filtering by subcriteria . Populate may be called more than once on the same query, as long as each call is for a different association.


1 Answers

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);
like image 156
JohnnyHK Avatar answered Sep 19 '22 17:09

JohnnyHK