【问题标题】:How to query and update mongodb subdocuments如何查询和更新mongodb子文档
【发布时间】: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"
}

【问题讨论】:

标签: javascript node.js mongodb express mongoose


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-04-05
    • 2017-08-15
    • 1970-01-01
    • 2023-04-04
    • 2020-10-18
    • 2020-07-21
    • 2023-01-30
    • 2011-08-04
    相关资源
    最近更新 更多