mongoose-advanced-populate
v1.0.1
Published
Advanced populate logic for Mongoose with nested and flexible path support.
Maintainers
Readme
mongoose-advanced-populate
A powerful Mongoose aggregation utility to handle advanced population logic — including nested paths, subpipelines, and flexible array/unwind handling — all with clean, intuitive syntax.
🔧 Installation
npm install mongoose-advanced-populate🚀 Usage
const advancedPopulate = require('mongoose-advanced-populate');
// Example: Populating comments with nested user data
const result = await advancedPopulate({
model: PostModel,
match: { _id: postId },
populates: [
{
from: 'comments',
localField: 'comments',
foreignField: '_id',
as: 'comments',
isArray: true,
pipeline: [
{
$lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'user',
}
},
{
$unwind: {
path: '$user',
preserveNullAndEmptyArrays: true,
}
}
]
}
]
});💡 When to Use
This package is perfect when:
- You need to populate deeply nested paths like
comments.user.profile.avatar. - You want to use aggregation subpipelines inside your population queries.
- You're working with denormalized MongoDB data and need joins across multiple levels.
- You want a cleaner abstraction over complex
$lookup,$unwind, and$projectpipelines.
Use it in large-scale apps where performance and query optimization is key — such as dashboards, analytics tools, multi-layered relationships, or large MongoDB schemas.
📘 Advanced Example: Multi-level Join
const result = await advancedPopulate({
model: Order,
match: { status: 'shipped' },
populates: [
{
from: 'customers',
localField: 'customerId',
foreignField: '_id',
as: 'customer',
isArray: false,
},
{
from: 'products',
localField: 'productIds',
foreignField: '_id',
as: 'products',
isArray: true,
pipeline: [
{
$lookup: {
from: 'suppliers',
localField: 'supplierId',
foreignField: '_id',
as: 'supplier'
}
},
{
$unwind: {
path: '$supplier',
preserveNullAndEmptyArrays: true
}
}
]
}
]
});This will return orders with populated customer info and each product enriched with its supplier.
🧠 Author & Contributions
Crafted with ❤️ to save you from Mongoose population hell. Contributions welcome!
