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

如何在Mongoose NestJS Schema中使用带动态键的嵌套对象

配置Mongoose Schema实现动态键嵌套对象存储

要实现你需要的动态键(语言标识)嵌套对象结构,只需将info字段的@Prop配置为Map类型,并指定值的Schema为Info即可,具体实现如下:

修改后的完整Schema代码

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

// 嵌套对象的Schema
@Schema()
export class Info {
  @Prop({ required: true }) // 可选:添加必填校验
  name: string;

  @Prop({ required: true }) // 可选:添加必填校验
  surname: string;
}

export type InfoDocument = Info & Document;
export const InfoSchema = SchemaFactory.createForClass(Info);

// 集合Schema
@Schema()
export class User {
  @Prop()
  age: number;

  @Prop()
  role: string;

  // 核心配置:指定为Map类型,值的结构遵循InfoSchema
  @Prop({ type: Map, of: InfoSchema })
  info: Record<string, Info>;
}

export type UserDocument = User & Document;
export const UserSchema = SchemaFactory.createForClass(User);

配置说明

  • type: Map:告诉Mongoose该字段存储的是MongoDB的动态键值对结构,正好匹配你需要的en、fr这类动态语言标识键。
  • of: InfoSchema:指定Map中每个值的结构必须符合Info的Schema定义,确保每个语言对应的对象都包含name和surname字段,同时支持Mongoose的校验、类型转换等特性。

验证效果

配置完成后,你可以正常存储和读取如下格式的数据,Mongoose会自动校验info下每个动态键对应的对象结构是否合法:

{
  age: 20,
  role: 'user',
  info: {
    en: { name: 'John', surname: 'Smith' },
    fr: { name: 'Johny', surname: 'La`Smith' }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:02:26