Search code examples
mongoosenestjsnestjs-mongoose

how to reference nested documents in nestjs mongoose typescript


I'm new with nestjs. I use @nestjs/mongoose and I need to reference several fields in a nested object in my class schema and I don't know how to do it.

The dietDays object must contain a date field and meals object that contain a 2 references to Meal schema.

What is the correct way to do it?

The code below shows how I tried to do it, as well as, the other way I tried was that create dietDays class and pass it to Prop type variable but in that scenario I am not able to reference to Meal schema because that was not a schema.

@Schema()
export class Diet {
  @Prop({ default: ObjectID })
  _id: ObjectID 

  @Prop()
  dietDays: [
    {
      date: string
      meals: {
        breakfast: { type: Types.ObjectId; ref: 'Meal' }
        lunch: { type: Types.ObjectId; ref: 'Meal' }
      }
    },
  ]
}


Solution

  • You should do it as following:

    Create a class which refers to each day in the diet ( logically make sense )

    @Schema()
    export class DayInDiet {
      @Prop() date: string;
      @Prop()
      meals:
        {
            breakfast: { type: Types.ObjectId, ref: 'breakfast' }
            launch: { type: Types.ObjectId, ref: 'launch' }
        }
    }
    

    Knowing that each of which breakfast and lunch should be a valid mongo schemas.

    If breakfast and lunch are not schemas, and you have a list of content you can pass this array as possible options for them inside the schema object.

    Another possible way

    @Schema()
    export class DayInDiet {
      @Prop() date: string;
      @Prop()
      meals: [
         { type: Types.ObjectId, ref: 'meal' } // note that meal should be the name of your schema
      ]
    }
    
    @Schema()
    export class Meal {
      @Prop() name: string;
      @Prop() type: 'launch' | 'breakfast'
    }
    

    simple note you are not required to make _id a prop of any schema

    Edit

    For the diet schema

    @Schema()
    export class Diet {
      // list of props
     // ...
      @Prop()
      dietDays: [
        { type: Types.ObjectId, ref: 'DayInDiet' }
      ]
    }