Home > front end >  How can I update just one atribute in my MySQL database using js?
How can I update just one atribute in my MySQL database using js?

Time:02-12

I have a little question about updating just one attribute and not all like in this code.

router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(req.body, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id="   id,
            });
        });
});

One register from my database looks like this:

{
  name: 'x',
  password: 'x',
  activated: 0
}

All I want to do is to make that 0 in 1 and I don't know what I have to change in my code because if I use this code, I will update all parameters (name, password, activated) and I want to update just one.

CodePudding user response:

It looks like you are using sequelize. In sequelize to update only one field you would pass an object with only one field into the .update method as it can be seen in the following snippet.

router.put("/update/:id", (req, res) => {
    const id = req.params.id;
    Account.update(
        {
          activated: req.body.activated
        }, {
            where: { id: id },
        })
        .then((num) => {
            if (num == 1) {
                res.send({
                    message: "Informatiile au fost actualizate cu succes.",
                });
            } else {
                res.send({
                    message: `Nu pot actualiza informatiile pentru contul cu id=${id}.`,
                });
            }
        })
        .catch((err) => {
            res.status(500).send({
                message: "Eroare actualizare date pentru id="   id,
            });
        });
});
  • Related