如何通过description字段更新Mongoose数组中的对象
问题
我想要更新数据库中的数据,但数组内的每个对象没有独立ID,只能通过description字段识别。我需要找到匹配该字段的数组对象,并将其description值更新为新内容。
数据结构如下:
{ "_id": { "$oid": "637c1064a2f047f5ab75ac42" }, "title": "this is a list", "todo": [ { "completed": false, "description": "a normal task" }, { "completed": false, "description": "this is another task" }, { "completed": false, "description": "another task" } ], "username": "lucas", "__v": 3 }
我尝试了以下代码,但无法实现需求:
List.findOneAndUpdate( {todo: {description: req.body.description}},// trying to find it here {$set:{todo : {description: req.body.newDescription}}}, //trying to change it here function(err, response) { console.log(err,response) } )
请问如何正确实现该更新操作?
解决方案
你的代码存在两个关键问题:
- 查询条件
{todo: {description: req.body.description}}是精确匹配整个数组对象,只有当todo数组里的对象和{description: xxx}完全一致(无其他字段)时才会匹配,但你的todo对象包含completed字段,因此无法匹配到目标文档。 - 更新语句
{$set:{todo : {description: req.body.newDescription}}}会直接覆盖整个todo数组,将原数组替换为仅含一个新对象的数组,而非修改匹配到的单个元素。
正确实现需要用到MongoDB的数组定位符$,它会匹配查询条件中第一个符合的数组元素,结合$set即可修改该元素的指定字段:
List.findOneAndUpdate( // 查询条件:定位包含目标description的todo元素的文档 { "todo.description": req.body.description }, // 更新操作:修改匹配到的todo元素的description字段 { $set: { "todo.$.description": req.body.newDescription } }, { new: true }, // 可选配置:返回更新后的文档,默认返回更新前的原始文档 function(err, response) { console.log(err, response); } );
多匹配元素的处理
如果todo数组中存在多个description相同的元素,上述代码仅会修改第一个匹配项。若需要批量修改所有匹配元素,需使用数组过滤操作符[<identifier>]:
List.findOneAndUpdate( { "todo.description": req.body.description }, { $set: { "todo.$[elem].description": req.body.newDescription } }, { arrayFilters: [{ "elem.description": req.body.description }], new: true }, function(err, response) { console.log(err, response); } );
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

