Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

533
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda