【发布时间】:2020-02-11 22:36:36
【问题描述】:
所以,我正在尝试更新 MongoDB 中的子文档,我正在使用 express,并且我有以下路线来查找要更新的确切对象,目前我只能用新文档替换整个文档,如果我这样离开它可以吗,或者是否有一个 MongoDB/mongoose 操作/功能可以帮助我根据用户提供的内容更新字段,例如,如果他们只是提供要更新的标题或优先级.我知道我不必只使用模式来更新一个属性,我正在尝试寻找一种替代方法来使用链 fo - elseif 或 switch 语句。
app.put('/updateTodoInProject/:id/:todo_id', (req,res)=>{ //':id' represents the id of the project in which the todo is
const collection = db.collection('projects');
const todo = new Todo({title: req.body.title, description: req.body.description, priority: req.body.priority});
collection.updateOne({_id: mongo.ObjectID(req.params.id),
todos: {$elemMatch: {_id: mongo.ObjectID(req.params.todo_id)}}
},{
$set: {
"todos.$": todo
}
},function(err, results) {
if (err){
console.log(err);
res.send('');
return
}
res.send(results)
});
});
我尝试更新的对象如下所示:
{
_id: "5e3bf72db5074c1e205409f5",
todos: [
{
_id: "5e42bef746bae7728c68384f",
title: "cool title 1",
description: "cool description 2",
priority: 1
}
],
title: "hjskadjshd"
}
【问题讨论】:
-
这个网站上有很多关于您的问题的答案。例如:stackoverflow.com/questions/5646798/…、stackoverflow.com/questions/29012328/… 等等。请先搜索一下。
-
这能回答你的问题吗? MongoDB: Updating subdocument
-
@whoami,是的,有点,我想不出我们的“multi”来根据请求中提供的数据更新文档的某些部分
标签: javascript node.js mongodb express mongoose