'Mongoose how joining tables if one of them is multiple deep
I am trying to make it so each user can only see their programs as part of a workout related fullstack app. However, the program schema is a connected to a workout schema, which is connected to an exercise schema, etc. I connected the userSchema to to the ProgramSchema like this:
const userSchema = mongoose.Schema({
name : { type: String, required: true },
email : { type: String, required: true },
password : { type: String, required: true },
id : { type: String },
}, {
timestamps: true,
})
// a virtual link to the Programs model
// this is so we can see each task pertaining to a specific user
userSchema.virtual('programs', {
ref: 'Program',
localField: '_id',
foreignField: 'creator'
})
Here is the ProgramSchema file:
const programSchema = mongoose.Schema({
program_name:{
type: String,
},
creator: { // the req.userId of the user
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
workouts:[{
type: mongoose.Types.ObjectId,
ref: 'Workout'
}]
})
And i am trying to query the user programs like this, but its not working! I am kind of stuck on how to query it correctly. Any help would be appreciated.
const getPrograms = async (req, res) => {
try{
await req.user.populate({
path: 'programs',
populate:{
path: 'workouts',
populate: {
path: 'exercises',
populate: {
path: 'sets'
}
}
}
}).execPopulate()
res.status(200).send(req.user.programs)
} catch (e) {
res.status(500).send(e)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
