npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

paginex-mongoose

v1.1.0

Published

Un plugin de paginación con agregación simple y reutilizable para Mongoose.

Downloads

33

Readme

paginex-mongoose

Un plugin de paginación flexible y fácil de usar para Mongoose, diseñado para simplificar la paginación de consultas en aplicaciones que utilizan Mongoose con MongoDB.

Características

  • Fácil de integrar con cualquier esquema de Mongoose.
  • Soporte para paginación personalizada y agregaciones adicionales.
  • Conversión automática de IDs de string a ObjectId para consultas.
  • Proporciona información detallada de la paginación como el total de documentos, páginas, y más.

Requisitos

Este paquete requiere Mongoose versión 5.x.x o superior. Asegúrate de tener Mongoose instalado en tu proyecto:

npm install mongoose

Instalación

Para instalar el paquete, ejecuta el siguiente comando en tu terminal:

npm install paginex-mongoose

Uso

Primero, importa el plugin y aplícalo a tu esquema de Mongoose.

const mongoose = require('mongoose');
const { paginatePlugin } = require('paginex-mongoose');
const { Schema } = mongoose;

const mySchema = new Schema({
  // tu definición del esquema aquí
});

// Aplicar el plugin de paginación al esquema
mySchema.plugin(paginatePlugin);

const MyModel = mongoose.model('MyModel', mySchema);

Types para NestJS


import { Field, ID, Int, ObjectType } from "@nestjs/graphql";
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import GraphQLJSON from "graphql-type-json";
import * as mongoose from 'mongoose';

export interface TuSchemaModel extends mongoose.Model<TuSchema> {
  paginateCollection(opts: PaginateOptions): Promise<PaginateResult<TuSchema>>;
}

@Schema({
  toJSON: { virtuals: true, getters: true },
  toObject: { virtuals: true, getters: true },
})
@ObjectType({ description: 'Tu Schema Description' })
export class TuSchema {
  @Field(type => [GraphQLJSON], { nullable: true })
  docs: JSON;

  @Field(type => Boolean)
  hasNextPage: boolean;

  @Field(type => Boolean)
  hasPreviousPage: boolean;

  @Field(type => Int)
  page: number;

  @Field(type => Int)
  pageSize: number;

  @Field(type => Int)
  totalDocs: Number;

  @Field(type => Int)
  totalPages: number;

}

export const TuSchemaFactory = SchemaFactory.createForClass(TuSchema);

No olvidar el:


import { paginatePlugin } from 'paginex-mongoose/paginate';
TuSchema.plugin(paginatePlugin)

Paginando Resultados

Para paginar los resultados de una consulta, usa el método paginateCollection proporcionado por el plugin en tu modelo:

async function getPaginatedResults() {
  const options = {
    page: 1, // Página actual
    pageSize: 10, // Cantidad de documentos por página
    additionalAggregations: [/* Agregaciones adicionales si se necesitan */]
  };

  const result = await MyModel.paginateCollection({
    query: {/* tu consulta de búsqueda aquí */},
    options: options
  });

  console.log(result);
  // {
  //   docs: [], // Los documentos de la página actual
  //   totalDocs: 0, // Total de documentos que coinciden con la consulta
  //   totalPages: 0, // Total de páginas
  //   page: 1, // Página actual
  //   pageSize: 10, // Tamaño de página
  //   hasNextPage: false, // Indica si hay una próxima página
  //   hasPreviousPage: false, // Indica si hay una página anterior
  // }
}

Opciones de Paginación

El método paginateCollection acepta un objeto de opciones que te permite personalizar la consulta de paginación. Las opciones disponibles incluyen:

  • page: La página actual que deseas recuperar.
  • pageSize: El número de documentos por página.
  • additionalAggregations: Un array de agregaciones adicionales de Mongoose que deseas aplicar a la consulta.

Contribuciones

¡Las contribuciones son siempre bienvenidas! Si tienes una sugerencia para mejorar este plugin, no dudes en crear un issue o un pull request.

Licencia

Este proyecto está licenciado bajo la Licencia MIT - ver el archivo LICENSE.md para más detalles.