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

1
  • Have you used $push in findOneAndUpdate? It should work. Commented Nov 20, 2018 at 17:22

1 Answer 1

2
UserGrades.findOneAndUpdate({ user: id }, { $push: { StudentGrades: gradeFields }}, { new: true }, function(err, raw) {
    if (err) {
        res.send(err);
    } else {
        res.send(gradeFields);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.