如何在NestJS中用Mongoose的@Prop()定义含动态键的对象数组?
NestJS Mongoose 中定义动态键值对数组的 body 字段
针对你给出的数组格式(元素为单个动态键值对的对象),可以按以下方式配置 @Prop 装饰器和类型:
场景1:键名完全不固定
如果数组里的对象键是动态变化的(比如key1、key2这类无固定名称的键),用下面的写法:
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class Entity extends Document { @Prop({ type: [{ type: Map, of: String }] }) // 若值类型不固定,把of改成any;如果是数字就用Number body: Record<string, any>[]; } export const EntitySchema = SchemaFactory.createForClass(Entity);
- Mongoose 层面用
Map类型存储单个键值对,外层套数组表示这是一组键值对对象。 - TypeScript 类型用
Record<string, any>[]描述“任意键值对对象组成的数组”,能获得类型提示。
场景2:键名有固定可选范围
如果数组里的对象只能用预设的几个键(比如只能是key1或key2),可以用联合类型约束:
@Prop({ type: [{ type: Object, required: true }] }) body: Array<{ key1?: string } | { key2?: number }>;
这里根据你实际的值类型调整string/number,required: true可以确保数组元素不为空。
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

