0

I have a document in mongoDB structured like that

_id: ObjectId("generatedByMongo"),
name: {
    required: true,
    type: String,
    trim: true
},
last: {
    required: true,
    type: String,
    trim: true
},
grades: [{
    grade: {
       _id: ObjectId(""),
       grade: Number,
       date: date 
    } 

}]

And to server I send array of objects containing 3 fields

[
 {studentId}, {gradeId}, {newGrade}
]

What I'm trying to accomplish is I want to find in within that user collection grade with given gradeId and update it's value to newGrade. As far as I tried to do that I have done this

router.patch('/students/updateGrade',async(req,res) => {
        const studentId = req.body.updateGradeArray[0].studentId;
        const gradeId = req.body.updateGradeArray[0].gradeId;
        const newGrade = req.body.updateGradeArray[0].newGrade;
        try {
            const student = await Student.find({_id: studentId})
                                         .select({'grades': {$elemMatch: {_id: gradeId}}});

        } catch(e) {
            console.log(e);
        }
    }
);
3
  • You have to use the update method (you are using the find method). Find can only read, and update can find the document and change the values. Commented Mar 18, 2020 at 9:20
  • Do you intend to update only the grade.grade(the number value)? or the entire grade object? Commented Mar 18, 2020 at 9:21
  • Hey guys, thanks for quick response. My goal is to update grades.grade(gradeId) Commented Mar 18, 2020 at 9:39

1 Answer 1

2

If you intend to update just grade.grade(the number value), try this:

Student.updateOne(
  // Find a document with _id matching the studentId
  { "_id": studentId },
  // Update the student grade
  { $set: { "grades.$[selectedGrade].grade": newGrade } },
  { arrayFilters: [{ "selectedGrade._id": gradeId }] },
)

Why this should work:
Since you are trying to update a student document, you should be using one of MongoDB update methods not find. In the query above, I'm using the updateOne method. Inside the updateOne, I am using a combination of $set and $[identifier] update operators to update the student grade.

I hope this helps✌🏾

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.