3

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' }
      }
    },
  ]
}

1 Answer 1

2

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' }
  ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer, but i'm little bit confused about Diet schema that should contain array of diet days (according to your answer DayInDiet). how do I use DayInDiet schema in my Diet schema? and thanks again :))
@soheib I've edited the answer according to final Diet schema

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.