I am trying to populate a document nested inside an array of objects, and nothing seems to work.
I want to populate the workout field inside this Program document.
This is the Program document:
const ProgramSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: "User", required: true },
program: [
{
day: {
type: String,
required: true,
enum: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
},
restDay: { type: Boolean },
workout: { type: Schema.Types.ObjectId, ref: "Workout" },
},
],
});
const Program = mongoose.model("Program", ProgramSchema);
This is the Workout Document:
const WorkoutSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
trainingDayName: {
type: String,
enum: ['A', 'B', 'C', 'D', 'FB', 'aerobic'],
required: true,
},
name: { type: String, required: true },
description: { type: String },
exercises: [
{
muscles: [{ type: String }],
name: { type: String, required: true },
description: { type: String },
sets: { type: Number, required: true, min: 1, max: 7 },
reps: { type: Number, required: true, min: 1, max: 50 },
},
],
time: { type: Number, min: 10, max: 300 },
});
const Workout = mongoose.model('Workout', WorkoutSchema);
CodePudding user response:
Turns out The solution is the following syntax:
const program = (await Program.findOne({ user: userId })
.populate(
'program.workout'
)) as ProgramType;