I recently started learning about the MERN stack, and in a project, I’m trying to add attendance records for every student from the same class.
My schema looks like this
const classesSchema = new Schema(
{
name:{type: String, required: true},
students: [{
// other fields go here
attendance:[{
date:{type: Date},
tHours:{type: Number},
aHours:{type: Number}
}],
}]
},
{
timestamps: true
}
)
To make it clear, imagine there are two students in the “students” array, I want for example to add every item from this array [{date: “2023-08-11”, tHours: 2, aHours; 1}, { “2023-08-11”, tHours: 2, aHours; 0}] to the student which has the same index.
I tried something like this but it didn’t work :
app.post("/api/classes/:id/students/attendance", async(req, res) => {
try {
req.body.forEach((element, index) => {
const attendanceObj = {
date: element.date,
tHours: element.tHours,
aHours: element.aHours
}
classModel.updateOne(
{_id: req.params.id},
{ $push: { "students.attendance": attendanceObj } }
);
res.json("A new attendance record has been added successfully!");
});
} catch (error) {
res.status(500).json({ error: "An error occured while adding a record!"});
}
});