使用猫鼬-分页-v2,我试图对集合的一个名为"Items“的子注释进行分组,但我没有成功。这是我的模型:
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']
}
}
);我试图这样做,但它返回整个文档,而不仅仅是我需要分页的子文档:
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 ); 到目前为止,我不知道如何实现它,但我希望你能帮助我。谢谢。
发布于 2022-02-01 07:04:58
我不确定MongoDB是否提供了一种开箱即用的方法,但是您可以使用聚合$function来实现这一点。
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'
}
}
}
}
])如果您也想分页PettyCashItems,可以在$addFields阶段之前添加$skip和$limit阶段。
https://stackoverflow.com/questions/70935281
复制相似问题