skip to content

What does Mongoose 9's populate() send to MongoDB when a list of Order documents populates its user and product references?

level: middleimportance: must knowfreq 70%

answer

  1. a join done by the client
  2. one query per path and model
  3. $in over collected ids
  4. nested levels run in sequence
  5. filtering parents by ref fields

basics

~20 s

populate() runs the main query, then one extra find per populated path and referenced model, with $in over the collected ids, and assigns results in memory: a client-side join with extra round trips that cannot filter parents.

solid answer

~50 s

A path declared with `ref: 'User'` stores only an `ObjectId`. `Order.find().populate('user').populate('items.product')` runs the orders query first, then collects every referenced id and issues one `find({ _id: { $in: ids } })` on users and one on products, in parallel by default (`ordered: true` runs them one at a time, which transactions need), and swaps each id for the loaded document. So a page of 50 orders costs three queries, not 51, but each nested `populate` level waits for the level above. Missing references become `null`, or are dropped from arrays. Populate cannot filter or sort orders by a user field: the orders query runs before users are loaded, and `match` only filters the populated side. When you need that, or a single round trip, use a `$lookup` in `Model.aggregate()`, which returns plain objects and does not cast its pipeline.

code

javascript · 13 lines
javascript
// Three queries: orders, then users and products in parallel
const orders = await Order.find({ status: 'paid' })
  .sort({ createdAt: -1 })
  .limit(50)
  .populate('user', 'name email')
  .populate('items.product', 'title price')
  .lean();

// Matches nothing: the filter runs while user is still an ObjectId
const none = await Order.find({ 'user.email': '[email protected]' }).populate('user');

// Filters the populated side only: orders come back, user may be null
const some = await Order.find().populate({ path: 'user', match: { plan: 'pro' } });

go deeper

for a junior

Know that a ref path stores an ObjectId and that populate() replaces it with the referenced document by running another query.

for a middle

Explain the batching: one query per path and model with $in over the collected ids, paths in parallel, nested levels in sequence, and why match does not remove parents.

for a senior

Count round trips on a list endpoint, trim their payload with select and lean, and recognise when filtering or sorting by referenced fields means moving to a $lookup in Model.aggregate with its casting and plain-object trade-offs.

for a principal

Judge whether hot read paths should keep paying populate's extra queries or read from a shape designed for them, and set conventions for when aggregation pipelines are allowed.

## What populate is In Mongoose, a **reference** is a path that stores another document's `_id`, declared with a `ref` that names the target model: ```javascript const orderSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User' }, items: [{ product: { type: Schema.Types.ObjectId, ref: 'Product' }, qty: Number }] }); ``` `populate()` is Mongoose's way of replacing those ids with the referenced documents after a query. MongoDB does not see a join: Mongoose performs it in your Node process with extra queries. The Mongoose docs describe populated paths as being replaced with documents returned by "performing a separate query before returning the results". ## The queries it issues For `await Order.find({ status: 'paid' }).limit(50).populate('user').populate('items.product')`: 1. Mongoose runs the orders query and receives up to 50 orders. 2. For each populated path it collects the ids found in those orders and builds one query per referenced model, filtered by `{ _id: { $in: ids } }`. 3. Separate paths are populated in parallel by default, so the users query and the products query run concurrently. Setting `ordered: true` runs them one at a time, which multi-document transactions require. 4. Results are matched back to each order by id and assigned in place of the `ObjectId`. That is **three** queries for the page, not one per order. The cost grows in other ways: - **Nested populate** (`populate({ path: 'user', populate: { path: 'company' } })`) needs the users before it knows which companies to load, so each level adds a sequential round trip. - **`perDocumentLimit`** runs a separate populate query per parent document, because the plain `limit` option applies to the whole batch, not to each order. - **Very large id sets** are split into per-document queries so the `$in` filter stays under MongoDB's 16 MB query size limit. - **Shared references** are loaded once: orders by the same user share one populated object unless you set `clone: true`. ## What populate cannot do - **Filter parents by referenced fields.** `Order.find({ 'user.email': email }).populate('user')` matches nothing, because the orders filter runs while `user` is still an `ObjectId`. The `match` option filters the populated documents, so a non-matching user becomes `null`, but the order is still returned. - **Sort parents by referenced fields**, for the same reason. - **Guarantee the reference exists.** A deleted user becomes `null`; a missing entry in an array of references is removed unless `retainNullValues` is set. - **Avoid the extra round trips.** However well batched, it is at least one query per populated path. Use `select` on the populated path (`populate('user', 'name email')`) to load only what the response needs, and `lean()` to skip hydrating both the orders and the populated users. ## populate versus $lookup in Model.aggregate When an endpoint must filter or sort orders by a user field, or wants one server round trip, the alternative is a `$lookup` stage in `Order.aggregate()`. What the stage does on the server belongs to the MongoDB aggregation material; what Mongoose changes is the contract around it: | | `find().populate()` | `Model.aggregate()` with `$lookup` | |---|---|---| | Where the join runs | in Mongoose, with extra queries | on the server, one command | | Filter or sort by joined fields | no | yes | | Filter casting | yes, the parent filter is cast | no, you pass `ObjectId` and `Date` values yourself | | Result type | Mongoose documents, or plain objects with `lean()` | always plain objects | | Middleware | `find` query hooks | `aggregate` hooks only | | Reads like | the schema's `ref` paths | a hand-written pipeline | Populate is the right default for "load these orders and show who placed them". Reach for `Model.aggregate()` when the question is about the joined data itself, such as orders whose customer is on a given plan. ## Seeing the round trips Setting `mongoose.set('debug', true)` makes Mongoose print each operation it sends, which is the quickest way to count what a list endpoint really costs: - one line for the orders `find`; - one `find` per populated path and model, each with an `_id` `$in` filter; - one more line per nested level, after the level above has finished. If the count grows with the page size rather than with the number of populated paths, look for `perDocumentLimit`, a populate inside a loop, or `doc.populate()` called per document in application code.

  • In Mongoose, why does populate({ path: 'reviews', options: { limit: 2 } }) give some orders no reviews?
    The plain `limit` applies to the single batched query for all parents, so Mongoose asks for roughly `numDocuments * limit` reviews in total and some orders receive none. `perDocumentLimit: 2` gives each order its own limit, at the price of one populate query per order.
  • How do you populate a reference inside a document you already loaded in Mongoose?
    Call `await doc.populate('user')` on the document, or `await Order.populate(docs, { path: 'user' })` for an array of documents or plain objects. Both issue the same batched `$in` query a query-level `populate()` would, and `doc.populated('user')` tells you whether a path currently holds populated data.

Populate works like a clerk with a stack of order slips that carry only customer numbers: the clerk writes every number on one list, makes a single trip to the customer files, then clips each card to its slip. It is one trip per kind of file, not one per slip, but the clerk cannot sort the slips by customer name before that trip.

  • populate() makes MongoDB join the collections inside the original query.
  • populate() runs one query per parent document returned.
  • The match option filters out parents whose reference does not match.
  • You can filter orders by user.email once user is populated.
  • Model.aggregate with $lookup returns hydrated Mongoose documents.