首页 > 解决方案 > 更新 mongoDB 中的单个项目,同时保持其余项目相同

问题描述

我正在使用一个 mongoDB,其中每个对象(我认为这是一行)有大约 30 个项目(我认为这些项目是列),我想使用一个更新函数,以便每个对象中只有一个项目被更新时它被调用,同时保持其余部分相同。下面是我正在使用的代码。

    const handleTeamUpdate = (id, column, value) => {
        const obj = {
            [column]: value
        };
        axios
            .post('http://localhost:4000/todos/update/' + id, obj)
            .then(() => {
                console.log(`Team updated`)
                fetchTeams() // refresh the teams
            })
            .catch(error => console.error(`There was an error updating.`))
    }
todoRoutes.route('/update/:id').post(function (req, res) {
    Todo.findById(req.params.id, function (err, todo) {
        if (!todo)
            res.status(404).send("data is not found");
        else
             todo.Team_Name = req.body.Team_Name;
             todo.Team_Manager = req.body.Team_Manager;
             todo.Department = req.body.Department;
             todo.Location = req.body.Location;
           // 26 more columns below the above

                todo.save().then(todo => {
                    res.json('Todo updated!');
                })
                    .catch(err => {
                        res.status(400).send("Update not possible");
                    });
    });
});

我当前的代码似乎要做的是更新我指定的项目(我在我的代码中将此称为列),但随后似乎删除/使所有其他“列”无效 - 我正在寻找一种解决方案来更新我指定的列但是还保持所有其他列相同 - 如果我不必在我的 Update 函数中将每一列声明为参数,我会更喜欢,因为它会使代码更加混乱。

标签: reactjsmongodbexpressaxios

解决方案


而不是 POST

  1. 当您想要修改已经是资源集合一部分的单一资源时,请使用PUT 。

  2. 如果请求更新部分资源,请使用PATCH 。


推荐阅读