NestJS Mongoose中如何为数组内对象自动添加_id
问题
我正在使用NestJS框架搭配Mongoose,希望为数组中的所有对象自动添加_id。我的Schema定义如下:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; export type PropModel = newSchemaDetail & Document; @Schema() export class Prop3 { @Prop({ type: String, required: true }) prop3.1: string; @Prop({ type: String, required: true }) prop3.2: string; } @Schema() export class Prop4{ @Prop({ type: String, required: true }) prop4.1: string; @Prop({ type: String, required: true }) prop4.2: string;} @Schema() export class newSchemaDetail { @Prop({ type: String, required: true }) prop1: string; @Prop({ type: String, required: false }) prop2: string; @Prop({ type: Array<Prop3>, required: true }) prop3: Prop3[]; @Prop({ type: Prop3, required: true }) prop4:Prop4 } export const PropSchema = SchemaFactory.createForClass(newSchemaDetail);
当前实际生成的结果为:
{ "prop1": "xyz", "prop2": "abc", "prop3": [ { "prop3.1": "kgkhkmfe", "prop3.2": "nbjfmlkgh" } ], "prop4":{"_id":"646b99d74abf7c25e21tx85","prop4.1":"test","prop4.2":"test2"}, "_id": "646c99e74bcf7b25d21cyb85", "__v": 0 }
期望得到的结果为:
{ "prop1": "xyz", "prop2": "abc", "prop3": [ { "_id":"646b99d47abf7c56e21tx89", "prop3.1": "kgkhkmfe", "prop3.2": "nbjfmlkgh" } ], "prop4":{"_id":"646b99d74abf7c25e21tx85","prop4.1":"test","prop4.2":"test2"}, "_id": "646c99e74bcf7b25d21cyb85", "__v": 0 }
为何@Schema()注解对数组中的对象无效?是否我操作有误?请告知如何实现期望的结果。
解决方案
问题原因
你直接用Array<Prop3>作为类型时,Mongoose不会将其识别为嵌套Schema,只会当作普通的对象数组处理,因此不会自动生成_id。而prop4是直接引用Prop4的Schema类,会被正确识别为嵌套文档,所以自动生成了_id。
修正方法
修改prop3的@Prop装饰器配置,将类型指定为[Prop3],同时注意修正属性名的TS语法问题(含点号的属性需要用引号包裹):
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; export type PropModel = newSchemaDetail & Document; @Schema() export class Prop3 { @Prop({ type: String, required: true }) 'prop3.1': string; @Prop({ type: String, required: true }) 'prop3.2': string; } @Schema() export class Prop4 { @Prop({ type: String, required: true }) 'prop4.1': string; @Prop({ type: String, required: true }) 'prop4.2': string; } @Schema() export class newSchemaDetail { @Prop({ type: String, required: true }) prop1: string; @Prop({ type: String, required: false }) prop2: string; // 关键修改:用[Prop3]指定嵌套文档数组类型 @Prop({ type: [Prop3], required: true }) prop3: Prop3[]; @Prop({ type: Prop4, required: true }) prop4: Prop4; } export const PropSchema = SchemaFactory.createForClass(newSchemaDetail);
原理说明
当在@Prop中使用[SchemaClass]的格式时,NestJS的Mongoose模块会将其解析为嵌套文档数组,此时Mongoose会自动为数组中的每个对象生成_id,和单个嵌套文档的处理逻辑一致。
另外注意:属性名包含点号时,必须用引号包裹,否则TypeScript会将其解析为对象属性访问,导致语法错误。
内容的提问来源于stack exchange,提问作者varsha kumari
相关产品推荐
相关产品推荐

