Updating a single item in mongoDB whilst keeping the rest the same

Viewed 62

I am using a mongoDB where each object (I think of this as a row) has about 30 items (I think of the items as columns), I want to use an update function so that just a single item in each object is updated when its called whilst keeping the rest the same. Below is the code I am using.

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

What my current code seems to do is update the item I specify (I refer to this as column in my code) but then seems to delete/nullify every other 'column' - I am looking for a solution which updates the column I specify but also keeps every other column the same - I would prefer if I don't have to state each column as an argument in my Update function as it will make the code much more messy.

2 Answers

Instead of POST

  1. Use PUT when you want to modify a singular resource that is already a part of resource collection.

  2. Use PATCH if request updates part of the resource.

If not using Mongoose middleware or validations on the Todo model schema. Its better to use update() or updateMany() or findByIdAndUpdate() which essentially delegates the whole query to mongo server.

Example with findByIdAndUpdate() :

const updateObject = {
  Team_Name: req.body.Team_Name,
  Team_Manager: req.body.Team_Manager,
  Department: req.body.Department,
  Location: req.body.Location,
};

//if the properties in req.body are same as the fields to be update use spread syntax below
// const updateObject = {...req.body};
Todo.findByIdAndUpdate(req.params.id, updateObject, { new: true }, function (
  err,
  todo
) {
  if (err) {
    console.error("error occured!", err);
    return;
  }

  console.info("Updated object is::", todo);
});
Related