I'm usign nestjs with mongodb and i'm having somw difficulties nested relationship inside Object I have this kind of document stored in my db
{
"_id": {
"$oid": "6263d033c77035b3b8474b13"
},
"plannedTrip": [{
"date": {
"$date": "2022-04-13T19:53:00.834Z"
},
"location": {
"$oid": "6261b43815788cddf30c7351"
}
}]
}
and i have created this entity in nestjs
export type PlanTripDocument = PlanTrip & Document;
@Schema()
export class PlanTrip {
@Prop()
@Transform(({ value }) => value.toString())
id: MongooseSchema.Types.ObjectId
@Prop({type: [PlannedTripSchema]})
plannedTrip: [PlannedTrip]
}
export const PlanTripSchema = SchemaFactory.createForClass(PlanTrip);
and this is the "PlannedTrip"
export type PlannedTripDocument = PlannedTrip & Document;
export class PlannedTrip {
@Prop()
date: Date
@Prop({ type: MongooseSchema.Types.ObjectId, ref: Location.name })
@Type(() => Location)
location: Location
}
export const PlannedTripSchema = SchemaFactory.createForClass(PlannedTrip);
so in the service when i do
return await this.PlanTripnModel.find().populate('plannedTrip')
i expect to get back something like this:
[
{
"_id": "626332c990f43c292de0bcd4",
"plannedTrip": [
{
"date": "2022-04-13T19:53:00.834Z",
"location": {
"_id": "6261b43815788cddf30c7351",
"name": "nome",
"__v": 0
}
}
],
"__v": 0,
}
]
instead i'm getting this
[
{
"_id": "626332c990f43c292de0bcd4",
"plannedTrip": [
{
"date": "2022-04-13T19:53:00.834Z",
"location": "6261b43815788cddf30c7351"
}
],
"__v": 0,
}
]
can you give me some suggestions, thanks.
CodePudding user response:
In case you want to specify relation to another model, later for populating, the property should have type and ref.
So, in your 'PlanTrip' class, you should change 'plannedTrip' property to this:
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'PlannedTrip' }] })
plannedTrip: PlannedTrip[];