@penname/mongoose-page-aggregation
v1.0.4
Published
Standalone MongoDB Mongoose pagination utility via the power of aggregation pipelines
Readme
Mongoose Page Aggregation
A standalone MongoDB Mongoose pagination utility powered by aggregation pipelines. This library provides efficient cursor-based pagination for MongoDB queries using Mongoose.
Features
- Cursor-based Pagination: Efficient pagination using MongoDB aggregation pipelines
- Flexible Sorting: Support for ascending and descending sort orders
- Custom Queries: Filter documents with custom find queries
- Population Support: Populate related documents using Mongoose populators
- Grouping: Group results by specified fields with optional aggregations
- Type-Safe: Full TypeScript support with comprehensive type definitions
- Lightweight: Zero dependencies (Mongoose is a peer dependency)
- ESM & CJS: Supports both ES modules and CommonJS
Installation
npm install @penname/mongoose-page-aggregation mongooseOr with yarn:
yarn add @penname/mongoose-page-aggregation mongooseRequirements
- Node.js: 14.0.0 or higher
- Mongoose: 8.7.0 or higher
Quick Start
import mongoose from 'mongoose'
import { pageAggregation, DbPagerSortOrder } from '@penname/mongoose-page-aggregation'
// Define your schema
const UserSchema = new mongoose.Schema({
name: String,
email: String,
createdAt: { type: Date, default: Date.now },
active: { type: Boolean, default: true }
})
const User = mongoose.model('User', UserSchema)
// Basic pagination
async function getUsers() {
const result = await pageAggregation({
Model: User,
findQuery: { active: true },
pager: {
field: 'createdAt',
limit: 10,
sortOrder: DbPagerSortOrder.Descending
}
})
console.log('Users:', result.dbObjects)
console.log('Total:', result.total)
console.log('Can load more:', result.canLoadMore)
}API Reference
pageAggregation(config)
Main function for paginated queries.
Parameters
config: PageAggregationConfig
Model(required): Mongoose model to queryfindQuery(required): MongoDB query filter objectpager(required): Pagination configurationfield(required): Field to paginate on (typically a date or ID)limit(optional): Number of documents per page (default: 10)sortOrder(optional):DbPagerSortOrder.AscendingorDbPagerSortOrder.DescendingsortAsc(optional): Boolean alternative tosortOrderfrom(optional): Cursor object for fetching next pagegroupBy(optional): Group results by specified fields
shouldSecordarySortOnId(optional): Enable secondary sorting by_idpopulators(optional): Array of population configurationspostPopulatorFilter(optional): Filter after populationskipCache(optional): Skip caching for this queryrunQuery(optional): Custom query execution function
Returns
PageAggregationResult<D>
dbObjects: Array of paginated documentstotal: Total count of matching documentssize: Number of documents in current pagelimit: Limit used for paginationcanLoadMore: Whether more documents are availablefrom: Cursor object for next pagesortOrder: Sort order usedstartedAt: ISO timestamp when query startedfinishedAt: ISO timestamp when query finished
Examples
Pagination with Cursor
// First page
const firstPage = await pageAggregation({
Model: User,
findQuery: { active: true },
pager: {
field: 'createdAt',
limit: 10,
sortOrder: DbPagerSortOrder.Descending
}
})
// Next page
if (firstPage.canLoadMore) {
const nextPage = await pageAggregation({
Model: User,
findQuery: { active: true },
pager: {
field: 'createdAt',
limit: 10,
sortOrder: DbPagerSortOrder.Descending,
from: firstPage.from
}
})
}Grouping Results
const grouped = await pageAggregation({
Model: User,
findQuery: { active: true },
pager: {
field: 'createdAt',
limit: 10,
groupBy: {
fields: ['department'],
countAs: 'count'
}
}
})Population
const withPosts = await pageAggregation({
Model: User,
findQuery: { active: true },
pager: {
field: 'createdAt',
limit: 10
},
populators: [
{
Model: Post,
localField: '_id',
targetField: 'userId',
as: 'posts'
}
]
})Utility Functions
The library exports several utility functions:
isValidId(id): Check if a string is a valid MongoDB ObjectIdtoObjectId(id): Convert a string to MongoDB ObjectIdisValidDate(value): Check if a value is a valid dategetModelCollectionName(model): Get collection name from Mongoose modelcompute(fn): Execute a function and return its result
License
MIT © 2025 PennameHq
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
