I want to add _id automatically to all object inside an array.I am using mongoose with nestjs framework.
my schema looks like
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);
result
{
"prop1": "xyz",
"prop2": "abc",
"prop3": [
{
"prop3.1": "kgkhkmfe",
"prop3.2": "nbjfmlkgh"
}
],
"prop4":{"_id":"646b99d74abf7c25e21tx85","prop4.1":"test","prop4.2":"test2"},
"_id": "646c99e74bcf7b25d21cyb85",
"__v": 0
}
expected
{
"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
}
Why @Schema()
is not working with array of object or am I doing something wrong.Can anyone tell how to get my expected result.
Thanks in advance!
First you should create a schema for Prop3 like this:
const Prop3Schema = SchemaFactory.createForClass(Prop3);
And replace the line @Prop({ type: Array<Prop3>, required: true })
with the following.
@Prop({ type: [Prop3Schema], required: true })