简体   繁体   English

MongoDB - 更新对象内对象数组中的数据

[英]MongoDB - update data in array of objects within object

I have a document in mongoDB structured like that我在 mongoDB 中有一个这样结构的文档

_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并向服务器发送包含 3 个字段的对象数组

[
 {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 .我想要完成的是我想在给定的gradeId用户集合grade找到,并将其值更新为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:如果你打算只更新grade.grade(数值),试试这个:

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.由于您正在尝试更新学生文档,因此您应该使用未找到的 MongoDB 更新方法之一。 In the query above, I'm using the updateOne method.在上面的查询中,我使用了updateOne方法。 Inside the updateOne, I am using a combination of $set and $[identifier] update operators to update the student grade.在 updateOne 中,我使用$set$[identifier]更新运算符的组合来更新学生成绩。

I hope this helps✌🏾我希望这有帮助✌🏾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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