Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js MongoDB-更新对象中对象数组中的数据_Node.js_Mongodb - Fatal编程技术网

Node.js MongoDB-更新对象中对象数组中的数据

Node.js MongoDB-更新对象中对象数组中的数据,node.js,mongodb,Node.js,Mongodb,我在mongoDB中有一个这样结构的文档 _id: ObjectId("generatedByMongo"), name: { required: true, type: String, trim: true }, last: { required: true, type: String, trim: true }, grades: [{ grade: { _id: ObjectId(""), grade: Nu

我在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 
    } 

}]
我向服务器发送包含3个字段的对象数组

[
 {studentId}, {gradeId}, {newGrade}
]
我试图实现的是,我希望在用户集合
grade
中找到具有给定
gradeId
grade,并将其值更新为
newGrade
。就我试图这么做而言,我已经做到了

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

如果要仅更新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 }] },
)
为什么这样做有效:
因为您正在尝试更新学生文档,所以应该使用MongoDB更新方法之一not find。在上面的查询中,我使用的是方法。在updateOne中,我使用和update操作符的组合来更新学生成绩


我希望这有帮助✌ 如果要仅更新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 }] },
)
为什么这样做有效:
因为您正在尝试更新学生文档,所以应该使用MongoDB更新方法之一not find。在上面的查询中,我使用的是方法。在updateOne中,我使用和update操作符的组合来更新学生成绩


我希望这有帮助✌您必须使用update方法(您使用的是find方法)。“查找”只能读取,而“更新”可以查找文档并更改值。是否仅更新年级。年级(数字值)?还是整个等级的物体?嘿,伙计们,谢谢你们的快速反应。我的目标是更新成绩。成绩(gradeId)您必须使用更新方法(您使用的是查找方法)。“查找”只能读取,而“更新”可以查找文档并更改值。是否仅更新年级。年级(数字值)?还是整个等级的物体?嘿,伙计们,谢谢你们的快速反应。我的目标是更新成绩。成绩(gradeId)