简体   繁体   中英

MongoDB - update data in array of objects within object

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);
        }
    }
);

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✌🏾

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM