My DB has collections for users, educations and courses.
When the server starts, it is supposed to populate the educations with necessary data, including an array called mandatoryCourses, with selected courses. Code below:
educationData.forEach((education) => {
Educations.insert({
name: education.name,
nickname: education.nickname,
mandatoryCourses: []
});
education.courses.forEach((code) => {
let course = Courses.findOne({code: code});
Educations.update({name: education.name}, {
$addToSet: {
mandatoryCourses: course
}
});
});
});
This works fine, except for one detail:
The _id field that the course has is not in the course entry in mandatoryCourses, yet all the other attributes are there. Checking a console.log(course) shows that the course in fact does possess an _id, but it will not show in the array entry.
A similar operation is addCourse, where a user gets a course attach to itself. This operation works perfect, including the _id, code below:
let course = Courses.findOne({code: courseId});
Meteor.users.update(userId, {
$addToSet: {
courses: course
}
});
The use of courseId/code is correct. My suspicion is that the issue lies within the schema that mandatoryCourses uses. For reference, the user.courses field is initialized as an empty array, whereas mandatoryCourses is defined as an array of courses, [Course].
The Course schema in turn looks like this:
Courses.schema = new SimpleSchema({
name: {
type: String,
label: "Course name"
},
code: {
type: String,
label: "Course code"
},
points: {
type: Number,
label: "Points"
},
finished: {
type: Boolean,
defaultValue: false
}
});
Those are also the exact attributes that go into the mandatoryCourses array.
Should I somehow explicitly declare _id in the course schema? It appears to work just fine when courses are added to the Courses collection, only not when interacting with the array mandatoryCourses.
Thanks in advance.
Adding the _id field to the Courses schema does the trick.
I am still unsure about the interaction and would love for someone to clarify why it was necessary to include it for the case of mandatoryCourses, whereas it worked fine for other uses of the schema.