I am really confused on how to approach this problem. I want to populate my studyGroups array of my User model with a specific StudyGroup model. I obtain the specific user and studyGroup through the router (cuid: req.params.cuid for the users, and guid: req.params.guid for the studyGroup).
Here is what my code looks like:
User
const userSchema = new Schema({
cuid: { type: 'String', required: true },
firstName: { type: 'String', required: true },
lastName: { type: 'String', required: true },
studentId: { type: 'Number', required: true },
password: { type: 'String', required: true },
email: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
lastLogin: { type: 'Date', default: null, required: false },
studyGroups: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "studyGroup"
}
]
});
StudyGroup
const studyGroupSchema = new Schema({
guid: { type: 'String', required: true },
groupName: { type: 'String', required: true },
course: { type: 'String', required: true },
teacher: { type: 'String', required: true },
description: { type: 'String', required: true },
dateAdded: { type: 'Date', default: Date.now, required: true },
});
Route
router.route('/:cuid/studyGroups/:guid').post(UserController.addUserStudyGroups);
Here is where all the action happens. First I find the user, and now I want to add the whole studyGroup model object to the array. So my thought was to query the studyGroup using the guid: req.params.guid but don't know if that is the proper way.
Controller
export function addUserStudyGroups(req, res) {
User.findOne({ cuid: req.params.cuid }).populate('studyGroups').exec((err, studyGroups) => {
if (err) {
return res.status(500).send(err);
}
study
return res.json({ studyGroups });
});
}