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.
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