[英]MongoDB - update data in array of objects within object
我在 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}
]
我想要完成的是我想在給定的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 更新方法之一。 在上面的查詢中,我使用了updateOne方法。 在 updateOne 中,我使用$set和$[identifier]更新運算符的組合來更新學生成績。
我希望這有幫助✌🏾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.