Loopback模型必填字段请求时报Should NOT have additional properties错误求助
问题排查与解决方案
「Should NOT have additional properties」错误由Loopback内置的JSON Schema校验逻辑抛出,本质是客户端请求传入的字段不在当前模型定义的允许字段列表内,和你设置的必填属性没有直接关联,可按以下步骤排查解决:
- 核对前端请求体的字段拼写与字段范围:重点确认是否出现
internalProjectId拼写错误(如大小写不符、多余字符),或者传入了模型未定义的额外字段,常见的误传字段包括createTime、updateTime等自动生成字段,或是未在模型中配置的关系关联字段。 - 调整模型严格校验配置:默认Loopback模型会禁止传入未定义的字段,如果你确实有传入额外字段的需求,可以给
@model()装饰器添加配置strict: false,关闭额外字段校验,修改后的模型示例如下:
import {Entity, model, property} from '@loopback/repository'; @model({ settings: { // 关闭严格校验,允许传入模型未定义的额外字段 strict: false } }) export class InternalProjectServiceType extends Entity { @property({ type: 'string', id: true, generated: true, }) id?: string; @property({ type: 'string', required: true, }) internalProjectId: string; @property({ type: 'string', }) serviceTypeId?: string; constructor(data?: Partial<InternalProjectServiceType>) { super(data); } } export interface InternalProjectServiceTypeRelations { // describe navigational properties here } export type InternalProjectServiceTypeWithRelations = InternalProjectServiceType & InternalProjectServiceTypeRelations;
- 核对接口参数的校验模型:如果你的Controller层接口没有直接使用
InternalProjectServiceType作为请求体校验模型,而是自定义了DTO类,需要确认DTO中也定义了所有请求传入的字段。 - 检查id字段传入逻辑:当前模型的id配置为自动生成,如果前端在新增数据的请求中主动传入了
id字段,也可能触发校验错误,新增场景无需传id参数。
内容的提问来源于stack exchange,提问作者Ashot Markosyan
相关产品推荐
相关产品推荐

