Home > OS >  Update table with sequelize only if a value is provided (node js)
Update table with sequelize only if a value is provided (node js)

Time:10-18

I receive a data object from the front end like so:

module.exports.myModule = async (req, res) => {
  let data = req.body.data  
}

For instance, that object contains the following properties and values:

name : Michel,
age: 56,
city: Paris,

If I want to update my table, I can do:

myTable.update(data);

But, if one of the property is empty, the corresponding value in the database will become empty to.

Is there a way to update the row only if a value is provided, and keep the old value if not?

CodePudding user response:

It only validates the data before saving to the database, use the 'options : object' that are used in the 'save' of the data. see more information here: https://sequelize.org/api/v6/class/src/model.js~model#instance-method-save

CodePudding user response:

try this :

let updateValues={};
if (body.name) updateValues.name  = body.name ;
if (body.age) updateValues.age= body.age;
if (body.city) updateValues.city= body.city;

myTable.update(updateValues);

now only entered values in body will be updated

  • Related