Simple and easy-to-use pagination library for Mongoose (Node.js)

Overview

node-paginator

Simple and easy-to-use pagination library for Mongoose (Node.js)

npm version npm downloads official website

📚 Why node-paginator?

Every web developer should work on pagination at some point. We were using Mongo DB and node.js, and surprised by the fact that there is no single package we can just install and start using. If you're using Mongoose on Node.js and going to work on pagination? Then node-paginator is worth trying.

📦 Install

npm install @careerday-jobs/node-paginator

🪄 Basic Usage

import { NodePaginator } from '@careerday-jobs/node-paginator';

// Mongoose model you're going to look up
import { UserModel } from '/src/models/user.model.ts';

const paginatedResult = await NodePaginator.paginateByMongoose({
  pageNoParam: 1, // required
  pageSizeParam: 10, // required
  model: UserModel, // required
});

const { pageNo, pageSize, totalItemNo, totalPageNo, items } = paginatedResult;

🪄 Advanced Usage

  1. Use regex feature provided by MongoDB for simple search which is useful enough.
import { NodePaginator } from '@careerday-jobs/node-paginator';

import { UserModel } from '/src/models/user.model.ts';

const paginatedResult = await NodePaginator.paginateByMongoose({
  pageNoParam: 1, // required
  pageSizeParam: 10, // required
  model: UserModel, // required
  filteredFields: [ 
    'username', 
    'email', 
    'address'
  ], // field names you are trying to look up
  filter: 'michael' // search keyword
});

const { pageNo, pageSize, totalItemNo, totalPageNo, items } = paginatedResult;
  1. Add and queries and or queries you want to add on
import { NodePaginator } from '@careerday-jobs/node-paginator';

import { UserModel } from '/src/models/user.model.ts';

const paginatedResult = await NodePaginator.paginateByMongoose({
  pageNoParam: 1,
  pageSizeParam: 10,
  model: UserModel,
  filteredFields: [ 
    'username', 
  ],
  filter: 'michael',
  orQuery: { email: '[email protected]'}, // or query.  (should get user of which email address is '[email protected]', even if username does not include 'michael')
  andQuery: { company: 'google' } // and query (username should include 'michael' and he/she is working for google)
});

const { pageNo, pageSize, totalItemNo, totalPageNo, items } = paginatedResult;
  1. Putting sort option is possible. (Default is { _id: -1 })
import { NodePaginator } from '@careerday-jobs/node-paginator';

// Mongoose model you're going to look up
import { UserModel } from '/src/models/user.model.ts';

const paginatedResult = await NodePaginator.paginateByMongoose({
  pageNoParam: 1,
  pageSizeParam: 10,
  model: UserModel,
  filteredFields: [
    'username',
  ],
  filter: 'michael',
  orQuery: { email: '[email protected]'},
  andQuery: { company: 'google' },
  sortingOption: { createdAt: 1 } // show the oldest one first
});

const { pageNo, pageSize, totalItemNo, totalPageNo, items } = paginatedResult;
  1. Default maximum size of page is 100. But if you want it to exceed the limit, you can put one more parameter at the end.
import { NodePaginator } from '@careerday-jobs/node-paginator';

// Mongoose model you're going to look up
import { UserModel } from '/src/models/user.model.ts';

const paginatedResult = await NodePaginator.paginateByMongoose({
  pageNoParam: 1,
  pageSizeParam: 1000, // PLEASE DON'T DO THIS.....BUT SOMETIMES YOU NEED TO DO IT
  model: UserModel,
  filteredFields: [
    'username',
  ],
  filter: 'michael',
  orQuery: { email: '[email protected]'},
  andQuery: { company: 'google' },
  sortingOption: { createdAt: 1 },
  isNoMinResultLimit: true // If you want the page size to exceed 100, you should set this true
});

const { pageNo, pageSize, totalItemNo, totalPageNo, items } = paginatedResult;

Input Parameters

parameter type description
pageNoParam (required) number current page number
pageSizeParam (required) numer maximum number of data to display on a page
model (required) Model<any> Mongoose model instance you want to look up
filteredFields string[] field names of the model you want to look up
filter string search keyword
orQuery FilterQuery custom OR query
andQuery FilterQuery custom AND query
sortingOption SortingOption sort options applied to pagination results. (default: { _id: -1 })
isNoMinResultLimit boolean If page size can exceed 100 (default: false)

Output Example

PaginatedResult {
      pageNo: 1,
      pageSize: 20,
      totalItemNo: 100,
      totalPageNo: 5,
      items: [
        {
          _id: new ObjectId("632a8d60d7b81199ad39d674"),
          email: '[email protected]',
          name: 'Hermann80',
          age: 71
        },
        {
          _id: new ObjectId("632a8d60d7b81199ad39d673"),
          email: '[email protected]',
          name: 'Agustina7',
          age: 58
        },
        ...
      ]
    }

Pagination Library On Frontend

Looking for a library which supports pagination on frontend? Why don't you check out react-paginator? It's way more efficient when you try both packages!

Contributors

@kunhokimcareerday

@starseeder0309

🔑 License

MIT @ 2022 CareerDay

You might also like...

A jQuery plugin for making html tables searchable and sortable with pagination

jQuery.fancyTable A jQuery plugin for making html tables searchable and sortable with pagination. Live demo See a live demo on CodePen Installation Us

Dec 19, 2022

URL Shortener API in NodeJS supporting pagination, sort params and lot more

URL Shortener API in NodeJS supporting pagination, sort params and lot more

node-url-shortener Built with ❤️ in NodeJS A simple URL Shortner REST API that uses shortid npm package to generate short endpoints for your long URL.

Sep 22, 2022

A handler to create embedded pages with buttons for pagination.

➝ Whats that • A handler to create embedded pages with buttons for pagination. ➝ Requirements • ["Handler"] pages.js • [Example command] embed.js ➝ Us

Oct 30, 2022

School App / Back-End with MongoDB / mongoose / Express / TS

TEST Api Dependencies El mati se la come es por eso que en 1998 la guerra fria se llevo a mas de la mitad del activo del pais "dependencies": { "axios

Jun 10, 2022

🚀 A mongoose plugin to monetize your apis in few lines of code

🚀 A mongoose plugin to monetize your apis in few lines of code

Stripe Mongoose Api Stripe Mongoose Api is a Mongoose plugin that simplifies building checkout and payment system for apis with stripe. It will provid

Dec 29, 2022

Breve explicacion de Mongoose, asi como un codigo con las operaciones CRUD

Breve explicacion de Mongoose, asi como un codigo con las operaciones CRUD

Introduccion a Mongoose ¿Qué es MongoDB? MongoDB es una base de datos NoSQL (Not Only SQL) y por ende no relacional que es utilizado para proyectos we

Mar 17, 2022

Uma Api dos 151 primeiros pokemons utilizando NodeJS, Typescript, Docker, MongoDB e Mongoose.

Uma Api dos 151 primeiros pokemons utilizando NodeJS, Typescript, Docker, MongoDB e Mongoose.

Pokedex API Tópicos Preview Sobre o Pokedex Api Tecnologias Instalação e uso Preview Clique aqui para ter acesso a um preview da Api. Sobre o Pokedex

Nov 27, 2022

Next-level mongoose caching layer with event based cache clearing

SpeedGoose ## About The Project This project is a next-level mongoose caching library which is fully written in typescript. It's caching on two levels

Dec 15, 2022

jQuery based scrolling Bar, for PC and Smartphones (touch events). It is modern slim, easy to integrate, easy to use. Tested on Firefox/Chrome/Maxthon/iPhone/Android. Very light 7ko min.js and 1Ko min.css.

Nice-Scrollbar Responsive jQuery based scrolling Bar, for PC and Smartphones (touch events). It is modern slim, easy to integrate, easy to use. Tested

Jan 18, 2022
Owner
CareerDay
Our mission is to help people find opportunities and chances to grow their career
CareerDay
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A simple javascript library for pagination, compatible with Bootstrap.

Easy Pagination JS A simple library for pagination, compatible with Bootstrap. Check my website here. Demo Check this Demo here. Example Import the fi

Wilfredo Paiz 18 Aug 5, 2022
Set up and build a Node.js REST API using Typescript, Express, Mongoose with a maintainable and scalable structure.

Introduction Create a maintainable and scalable Node.js REST API with TypeScript, Express and Mongoose. The project structure is based on MVC and foll

Adam Khomsi 16 Nov 18, 2022
Create a maintainable and scalable Node.js GraphQL API with TypeScript, Express, Mongoose and Apollo Server.

Set up and build a Node.js GraphQL API using Typescript, Express, Mongoose with a maintainable and scalable structure

Adam Khomsi 7 Nov 4, 2022
REST API built with Node.js, MongoDB, Mongoose & TypeScript. I also dabbled with Docker and Caddy for deployments

REST API with Node.js, Mongoose & TypeScript Note: This repository includes the postman collection for the finished API Note 2: Make sure you add .env

Manuchimso Oliver 2 Sep 16, 2022
Mongoose Node.js Express TypeScript application boilerplate with best practices for API development.

Node TypeScript Boilerplate Mongoose The main purpose of this repository is to show a good end-to-end project setup and workflow for writing a Mongoos

Chirag Mehta 20 Dec 13, 2022
🧬 A type builder for pagination with prisma and type-graphql.

?? Prisma TypeGraphql Pagination Prisma TypeGraphql Pagination builds prisma pagination types for type-graphql. import { ... } from 'type-graphql'

Arthur Fiorette 2 Apr 21, 2022
Holy Qur'an Telegram Bot with pagination and audio, in Indonesian language.

quran-telegram-bot Contributions are Welcome! Demo @fio_quran_bot Run Tested on Node.js v14.x.x with NPM v6.x.x, Windows 10 and Ubuntu 18.04.6 LTS. Cr

Rioze 5 Oct 21, 2022