我正在使用node,nestjs和mongoose,我写了一个get调用并得到像

[
 {
    "_id": "5d4a9c0b1a6bcf14775c953c",
    "material_name": "ramboo",
    "material_status": 0,
    "is_admin_approved": true,
    "createdAt": "2019-08-07T09:38:19.237Z",
    "updatedAt": "2019-08-07T09:38:19.237Z",
    "id": "5d4a9c0b1a6bcf14775c953c"
}
]


这样的服务(material.service.ts)

async findAll(): Promise<IDMaterial[]> {
  return await this.materialModel.find({is_admin_approved: true});
  }


如何从结果中删除is_admin_approved字段,例如

[
 {
    "_id": "5d4a9c0b1a6bcf14775c953c",
    "material_name": "ramboo",
    "material_status": 0,
    "createdAt": "2019-08-07T09:38:19.237Z",
    "updatedAt": "2019-08-07T09:38:19.237Z",
    "id": "5d4a9c0b1a6bcf14775c953c"
}
]


如何以任何方式解决此问题,请帮助我?

最佳答案

您可以使用lodash is 函数从数组中的每个对象中省略is_admin_approved

async findAll(): Promise<Partial<IDMaterial>[]> {
  return this.materialModel
    .find({is_admin_approved: true})
    .then(data => data.map(item => _.omit(item.toObject(), 'is_admin_approved')));
}

您也可以在is_admin_approved dto类中将@Exclude标记为IDMaterial,然后将检索到的项目投射到此dto(plainToClass(IDMaterial, item))。
export class IDMaterial {
   // ...
   @Exclude()
   is_admin_approved: boolean;
  // ...
}

// ...
async findAll(): Promise<Partial<IDMaterial>[]> {
  return this.materialModel
    .find({is_admin_approved: true})
    .then(data => data.map(item => plainToClass(IDMaterial, item)));

}

10-10 00:24