how do I update an object in Sequelize

Viewed 411

I am new to Sequelize, and I'm trying to update an object, but it's not working. here is my code

const updateEmployee = async (req, res) =>{
    let {full_name, email, phone_number, address} = req.body

    const id = req.params.id;
    Employee.findOne({
        where: { id: id }
    })
        .then(employee => {
            employee.update({
                full_name: full_name.full_name,
                email: email.email,
                phone_number: phone_number.phone_number,
                address: address.address
            })
        })
}

please assist !!

2 Answers

You can use the update() method and add the search scope as second argument. The update() method is a Promise that returns an array with with one or two elements. The first element is always the number of affected rows. See the sequelize API documentation for more details on the update() method.

Your code should look something like this. I have not tested this so you might need to tweak the code a bit:

updateUser: async (req, res) => {
  try {
    await employee.update(req.body, { 
      where: { 
        id: req.body.id 
      } 
    })
    .then((result) => {
      // check the first element in the array if there are rows affected
      if (result[0] > 0) {
        res.status(200).send({ message: 'data found' });
      } else {
        return res.status(422).send({ message: 'no data found' });
      }
    })
  }
  catch(error) {
    console.log(error);
    return res.status(500).send({ message: 'updating user failed' });
  }
}

When you are using async function. It is best to use await also don't use promise based format this in below api first I am finding user with that id from database if its present it ill update user else it will throw error that there is no data with that id

updateUser: async (req, res) => {
    try {

        let data = await employee.findOne({
            where: {
                id: req.body.id
            }
        });
        if (data) {
            await employee.update(req.body, { where: { id: req.body.id } });
            return res.status(200).send({message: data found});
        }
        else {
            return res.status(422).send({message: no data found});
        }
    } catch (err) {
        console.log(err)
        return res.status(500).send({message: Internal server error);
    };
}
Related