Reputation: 228
So I have a student grades object
[
{
_id: '5bf43c42a09e1129b8f0cd4c',
user: '5bc89dec5f6e1103f808671b',
StudentGrades: [
{
_id: '5bf43daf58f0f803d4e9760b',
classCode: 'ENG1A0',
gradeLevel: 12,
credit: 1,
mark: 67
}
],
__v: 0
}
];
I use the following backend code to make entries into the database
router.put('/:user_id', function(req, res) {
let id = req.params.user_id;
const gradeFields = {
classCode: req.body.classCode,
gradeLevel: req.body.gradeLevel,
credit: req.body.credit,
mark: req.body.mark
};
if (gradeFields)
passport.authenticate('jwt', { session: false }),
UserGrades.findOneAndUpdate(
{ user: id },
{ $push: { StudentGrades: gradeFields } },
{ new: true },
{ unique: true },
function(err) {
if (err) {
res.send(err);
} else {
res.send(gradeFields);
}
}
);
});
Everything is working but at this time, a person can have duplicate classes.
In the express code i tried using {unique: true} and tried setting the classCode mongoose model to unique as well, but it didn't work. Help would be appreciated
Upvotes: 1
Views: 68
Reputation: 168
user_id
maps to an existing user. StudentGrade
with the supplied classCode
. router.put('/:user_id', async (req, res) => {
const { user_id } = req.params;
const gradeFields = {
classCode: req.body.classCode,
gradeLevel: req.body.gradeLevel,
credit: req.body.credit,
mark: req.body.mark
};
try {
// Authenticate with Passport
await passport.authenticate('jwt', { session: false });
// Grab user with this user_id
const existingUser = await UserGrades.findOne({ user: user_id });
if(!existingUser) {
// If user does not exist, throw 404
res.status(404).send("User with this ID does not exist");
}
// Check if user has classCode already on an existing StudentGrade
if(existingUser.StudentGrades.some(sg => sg.classCode === req.body.classCode)) {
res.status(409).send("Student already has grade with this class code.");
}
// Update user record with new StudentGrade and return updates document
const updatedUser = await UserGrades.findOneAndUpdate(
{ user: user_id },
{ $push: { StudentGrades: gradeFields } },
{ new: true }
);
res.status(200).send(updatedUser);
} catch (e) {
console.log('Failed to update user grades', e);
// Unknown server error, send 500
res.status(500).send(e)
}
});
Upvotes: 1