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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:50:29