Nested Populate
🎯 Function Overview
Nested populate lets you populate relations on documents that were already populated, so you can load a multi-level document graph with one chain.
Model schema examples on this page use the runtime-scoped s namespace passed by monSQLize. Application code does not need to import the root schema-dsl entry for these examples.
📖 How to use
1. Basic nested populate
Populate the posts association and then further populate the posts.comments association:
2. Nested populate object configuration
Nested populate also supports full configuration options:
3. Multi-level nested populate
Supports 3 or more levels of nesting:
4. Nesting multiple populates
Multiple associations can be populated simultaneously at a nested level:
5. Mix chained and nested populates
You can use both chained and nested populates:
📋 Complete example
Model Definition
Query example
Runtime behavior
- First-level populate can read from the collection named in
from. - If
frommatches a registered Model, monSQLize hydrates the related documents through that Model. - Nested populate continues only when the related collection has a registered Model, because the next relation set must come from that Model definition.
- The runtime applies
select,sort,skip, andlimitafter the related documents are loaded. - Nested populate has depth and cycle guards. If a nested path is invalid, the query fails with a user-facing argument error.
⚠️ Notes
1. Define Models for nested branches
First-level populate can load plain related documents from a collection. Nested populate needs a Model definition for the related collection, otherwise monSQLize has no relation metadata for the next hop:
2. Performance considerations
Nested populate executes multiple database queries. Keep the relation graph shallow and index foreign keys:
Optimization suggestions:
- Use
selectto select only necessary fields - Use
limitto limit the amount of associated data - Avoid deep relation graphs unless the user path really needs them
3. Circular reference
Avoid circular references leading to infinite recursion:
Solution: design nested paths deliberately, set explicit limits, and avoid bidirectional nested chains.
📊 Compatibility
🧪 Test cases
For complete test cases, please refer to:
test/integration/model/model-features.test.tstest/integration/model/model-schema-and-hooks.test.ts
Coverage includes:
- Basic nested populate
- Nested populate object configuration
- Three-level nesting
- Multiple nested populate paths
- Mixed chained and nested populate