1

Hi so I have an an array of object like this:

[
    {
        "_id": "5bf43c42a09e1129b8f0cd4c",
        "user": "5bc89dec5f6e1103f808671b",
        "StudentGrades": [
            {
                "_id": "5bf43daf58f0f803d4e9760b",
                "classCode": "ENG1A0",
                "gradeLevel": 12,
                "credit": 1,
                "mark": 67
            }
        ],
        "__v": 0
    }
]

Using node.js and mongoose I want add another object in the Student Grades array. The API code I have now is only updating the array and not appending to it. I was wondering whats the correct way to add another object to the StudentGrades array of objects.

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
    };
    passport.authenticate('jwt', { session: false }), UserGrades.update({ user: id }, gradeFields, function(err, raw) {
        if (err) {
            res.send(err);
        } else {
            res.send(gradeFields);
        }
    });
});

I also tried using UserGrades.findOneandUpdate but that was also doing the same thing, it was only editing the values in the object and not appending another object to it. I am guessing I have to push the values, but I am not sure how. Help would be appreciated

Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22
sharsart
  • 228
  • 5
  • 14

1 Answers1

2
UserGrades.findOneAndUpdate({ user: id }, { $push: { StudentGrades: gradeFields }}, { new: true }, function(err, raw) {
    if (err) {
        res.send(err);
    } else {
        res.send(gradeFields);
    }
});
Gaurav Bharti
  • 1,065
  • 1
  • 14
  • 22
Raunik Singh
  • 214
  • 1
  • 4