Typegoose嵌套鉴别器字段插入数组报错:无法将字段设为数组
问题:Typegoose嵌套鉴别器数组插入报错
使用MongoDB + Node.js(TypeScript) + Typegoose开发Web应用时,向PageSection类的contents字段(嵌套鉴别器数组)插入对象数组时,出现如下错误:
PageSection validation failed: contents: Tried to set nested object field `contents` to array ``
传入单个对象时无报错,但业务需要传入数组,尝试将@prop的type设置为() => [PageSectionContent]仍未解决。
问题原因
Typegoose中定义嵌套鉴别器数组时,若仅将type设为单个基类(PageSectionContent),Mongoose会默认把该字段解析为单个嵌套对象而非数组。即便手动指定type: () => [PageSectionContent],若鉴别器配置未适配数组场景,也会导致验证逻辑冲突,触发上述报错。
修复方案
需要明确将contents字段的类型配置为数组,并确保鉴别器正确绑定到数组元素上,具体修改如下:
修改PageSection类的contents字段配置
将原@prop配置中的type改为数组形式的函数返回值,同时确保鉴别器配置无误:
@prop({ required: true, // 明确指定为数组类型的嵌套鉴别器基类 type: () => [PageSectionContent], discriminators: () => [ { type: HtmlBlockContent, value: ContentType.htmlBlock }, { type: HeaderContent, value: ContentType.header }, { type: CodeBlockContent, value: ContentType.codeBlock }, { type: AlertMessageContent, value: ContentType.alertMessage } ], default: [], }) public contents!: PageSectionContent[];
额外验证点
- 确保测试数据中的
type值与ContentType枚举完全匹配(比如测试数据中的'header'对应ContentType.header) - 确认
contentsToInsert是合法的对象数组,每个元素都包含_id、type等必填字段
验证结果
修改后,使用原测试数据执行PageSectionModel.create操作,即可正常插入数组类型的contents字段,不会再触发验证错误。
内容的提问来源于stack exchange,提问作者Wai Yan Hein
相关产品推荐
相关产品推荐

