How to update MongoDB documents with arrays of sub-documents How to update MongoDB documents with arrays of sub-documents mongoose mongoose

How to update MongoDB documents with arrays of sub-documents


There are a few way to do this I'll answer point by point

Retrieve the scores for all students, or for a specific student (retrieve specific element in the scores array)

Class.findOne({ name: 'Grade 5 - Section A'})     .populate('scores.studentId')     .exec(function(err, class) {       if (err) throw err;       //now class.scores.studentId becomes ObjectStudent       //hence you have all scores for all students});

Add/ update/ delete a specific student's score, for a specific subject (in case of update or delete, retrieve a specific element in the scores[n].performance array; for add, append to the same array.

Class.findOneAndUpdate({name: 'Grade 5 - Section A'                        ,'scores.studentId': ObjectId('5776bd36ffc8227405d364d2')                        , 'scores.performance.subjectId' : ObjectId('577694ecbf6f3a781759c54a')}                        , {$set: {scores.performance. score: 50}}                        , function(err, data) {           if (err) throw err    });

I hope that helps