Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Pagination from Nodejs Mongoose subdocument

Using mongoose-paginate-v2 I am trying to Paginate a subcomment called "Items" of a collection but I have not succeeded. This is my model:

    const mongoosePaginate = require('mongoose-paginate-v2');

    const PettyCashItemsSchema = Schema (
    {
        pettyCashId:{
            type: Schema.Types.ObjectId,
            ref:'PettyCash',
            required: [true, 'La Caja Chica es Obligatoria']
        },
        user:{
            type: Schema.Types.ObjectId,
            ref:'Users',
            required: [true, 'El Usuario es obligatorio']
        },
        item: {
            type: Number,
            unique: true
        },    
        items:[{
            concept: {
                type: String,
                maxlength:50,
                required: [true, 'El Concepto es obligatorio']
            },
            incomeAmount:{
                type: Number,
                maxlength:50,
                default:0,
                required: [true, 'El Ingreso es obligatorio']
            },
            expenseAmount:{
                type: Number,
                maxlength:50,
                default:0,
                required: [true, 'El Egreso es obligatorio']
            },
            description: {
                type: String,
                maxlength:50,
                required: [true, 'La Observación es obligatoria']
            },
            status: {
                type: Boolean,
                default: true,
                required: [true, 'El Estatus es obligatorio']
            }
        }],
        status: {
            type: Boolean,
            default: true,
            required: [true, 'El Estatus es obligatorio']
        }
    }  
    );

And I am trying to do it in this way but it returns the entire document and not just the subdocument that I need paginated:

        const options = {
            lean: true,
            limit: 10,
            page: 1,
            read: {
              pref: 'secondary',
              items: [
                {
                    status: true,
                },
              ],
            },
          };
        
        let items = await PettyCashItems.paginate( { 'pettyCashId': pettyCashId }, options );
        
        res.json( items );  

Until now I don't understand how to achieve it but I hope you can help me. Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I am not sure if MongoDB provide a way to do this out of the box but you can use aggregation $function to achieve this.

PettyCashItems.aggregate([
    {
        $match: {
            pettyCashId: pettyCashId 
        }
    },
    {
        $addFields: {
            items: {
                $function: {
                    body: function(items) {
                        var skip = (page - 1) * limit
                        var to = skip + limit
                        return {
                            docs: items.slice(skip, to), 
                            totalDocs: items.length
                        }
                    },
                    args: ['$items'],
                    lang: 'js'
                }
            }
        }
    }
])

and if you wanna paginate PettyCashItems too, you can add $skip and $limit stages before $addFields stage

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda