繁体   English   中英

如何查询和更新mongodb子文档

[英]How to query and update mongodb subdocuments

所以,我正在尝试更新 MongoDB 中的一个子文档,我正在使用 express 并且我有以下路线来查找我想要更新的确切对象,目前我只能用一个新文档替换整个文档,可以吗如果我保持这样,或者是否有 MongoDB/mongoose 操作/函数可以帮助我根据用户提供的内容更新字段,例如,如果他们只提供要更新的标题或优先级。 我知道我不必使用模式来更新一个属性,我试图找到一种替代方法来使用 if - 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"
}

您可以根据用户输入的详细信息在外部创建一个完整的更新对象,然后像这样更新查询中的值

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');
    var updateObj = {'todos.$.title': req.body.title, 'todos.$.description': req.body.description, 'todos.$.priority': req.body.priority};
    collection.updateOne({_id: mongo.ObjectID(req.params.id),
        todos: {$elemMatch: {_id: mongo.ObjectID(req.params.todo_id)}}
    },{
        $set: updateObj
    },function(err, results) {
        if (err){
            console.log(err);
            res.send('');
            return
        }
        res.send(results)
    });
});

暂无
暂无

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

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