UNPKG

@dmxdev/mongoose-paginated-query

Version:
77 lines (76 loc) 3.44 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); /** * Paginates a Mongoose model query. * * @template T - The type of the documents being queried. * @param {Model<T>} schema - The Mongoose model to query. * @param {PaginationOptions} options - The pagination options. * @param {Record<string, any>} [query] - The query conditions. * @returns {Promise<{ * docs: T[]; * totalDocs: number; * limit: number; * page: number; * totalPages: number; * hasNextPage: boolean; * hasPrevPage: boolean; * }>} - An object containing the paginated results and pagination information. */ const mongoosePaginate = (_a) => __awaiter(void 0, [_a], void 0, function* ({ schema, options, query = {}, populate, select, }) { const { page = 1, limit = 10, sort = {} } = options; const skip = (page - 1) * limit; /** * Executes a paginated query on a MongoDB schema using Mongoose. * * @param schema - The Mongoose model/schema to query * @param query - The MongoDB query filter criteria * @param skip - Number of documents to skip * @param limit - Maximum number of documents to return * @param sort - Sort criteria for the query results * @param normalizedPopulate - Population options for referenced documents * @param select - Fields to include/exclude in the query results * @returns Promise containing a tuple of [documents array, total count] * @typeParam T - Type of the documents being queried */ try { const [docs, totalDocs] = yield Promise.all([ schema .find(query) // Find documents matching the query .skip(skip) // Skip the specified number of documents .limit(limit) // Limit the number of documents returned .sort(sort) // Sort the documents .populate(populate) // Populate referenced documents .select(select) // Select specific fields .lean() // Convert documents to plain JavaScript objects .exec(), // Execute the query schema.countDocuments(query), // Count the total number of documents matching the query ]); const totalPages = Math.ceil(totalDocs / limit); const hasNextPage = page < totalPages; const hasPrevPage = page > 1; return { docs, totalDocs, limit, page, totalPages, hasNextPage, hasPrevPage, }; } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; throw new Error(`Error during pagination: ${errorMessage}`); } }); exports.default = mongoosePaginate;