You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LoopBack 4中从OpenAPI Schema排除嵌套模型属性

在LoopBack中排除嵌套模型属性的方案

直接通过@requestBody()装饰器没法直接排除嵌套模型的属性,但有几种可行的方式实现你的需求:

1. 创建专用的精简模型子类

针对需要排除属性的嵌套模型,创建一个只保留所需属性的子类,然后在请求体中引用这个子类:

@model()
export class ChildModelWithoutId extends ChildModel {
  // 覆盖原属性,用never类型明确排除该字段
  @property({required: false, nullable: true})
  id?: never;
}

// 在控制器的请求体中使用调整后的结构
@post('/example')
async create(
  @requestBody({
    content: {
      'application/json': {
        schema: {
          type: 'object',
          properties: {
            description: {type: 'string'},
            childModel: {'$ref': '#/components/schemas/ChildModelWithoutId'},
          },
        },
      },
    },
  })
  requestBody: ParentModel & {childModel: ChildModelWithoutId},
) {
  // 处理请求逻辑
}

2. 手动定义请求体Schema

直接在@requestBody()里编写自定义Schema,精确控制嵌套模型的属性:

@post('/example')
async create(
  @requestBody({
    content: {
      'application/json': {
        schema: {
          type: 'object',
          properties: {
            description: {type: 'string'},
            childModel: {
              type: 'object',
              // 只列出需要保留的属性,未列出的自动排除
              properties: {
                name: {type: 'string'},
              },
              required: ['name'], // 按需设置必填项
            },
          },
        },
      },
    },
  })
  requestBody: {description?: string; childModel: {name: string}},
) {
  // 处理请求逻辑
}

3. 结合类型别名与模型Schema生成

使用TypeScript的Omit类型剔除不需要的属性,再通过getModelSchemaRef生成对应Schema:

// 定义剔除属性后的类型
type ParentModelWithoutChildId = Omit<ParentModel, 'childModel'> & {
  childModel: Omit<ChildModel, 'id'>;
};

@post('/example')
async create(
  @requestBody({
    content: {
      'application/json': {
        schema: getModelSchemaRef(ParentModelWithoutChildId, {
          exclude: [], // 可额外配置其他排除项
        }),
      },
    },
  })
  requestBody: ParentModelWithoutChildId,
) {
  // 处理请求逻辑
}

如果需要让调整后的类型被OpenAPI Components识别,可以包装成带@model()装饰器的类:

@model()
export class ParentModelWithoutChildId extends ParentModel {
  @property({schema: getModelSchemaRef(Omit<ChildModel, 'id'>)})
  childModel: Omit<ChildModel, 'id'>;
}

// 直接在请求体中引用这个新模型
@post('/example')
async create(
  @requestBody({
    content: {
      'application/json': {
        schema: getModelSchemaRef(ParentModelWithoutChildId),
      },
    },
  })
  requestBody: ParentModelWithoutChildId,
) {
  // 处理请求逻辑
}

内容的提问来源于stack exchange,提问作者naol arega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:36:08