'Want to change a model ObjectID value

I am creating a Student and Course relationship A student may have multiple courses. A one to many relationship.

This is made in Express and I'm using MongoDB. I have shorten the models to keep it simple

Student Model

const studentSchema = new mongoose.Schema({
    name: {type: String},
    courses: [{
        type: ObjectId,
        ref: 'class'
    }]})

Course Model

const classSchema = new mongoose.Schema({
    ClassId: {type: String,},
    Grade: {type: Number,},    })

Currently, what I have is when I update the grade, it will update the grade values for the course itself and not the course in the user courses.

router.put(....) const{username, courseId, grade} = req.params

const existingUser = await Student.findOne({username}).populate({
    path: 'courses',
    select:['ClassId','Grade']
})

const findCourse = existingUser.courses.find(
    x => x.ClassId == courseId
)

findCourse.Grade = parseInt(grade)
await findCourse.save()

The problem is this will change the grade for the course itself. Meaning any student that adds this course will have that grade too.

I'll explain what I want to do in Java/OOP terms if that helps.

I want the student object to have it's own course objects. At the moment, it seems like classes are static class objects.

I want to access that specific student courses and change that student grade of that specific course.

Please help, I already spent a couple of hours on this. In SQL, the student would have a reference key and be able to easily change their values, I'm having trouble in MongoDB.



Solution 1:[1]

Alright, I finally figured it out. In hindsight, it makes sense. Gave myself a break from coding and came back to see the problem.

Lets pretend we have two students and one course. This courses is seeded with data.

When a student A picks that course, they add it to their course array. When student B wants that course, they also get that exact course. Now they are sharing the course. Basically, they are sharing the same reference.

The solution to this is to still find the course. Now make a new course object, copy every value of the original to the copy. Save the copy to the database and now you add that course to the student. Now we can still register for courses and use the seeded data and students don't share anymore.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 User4u