Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .update() value to NULL in sequelize

I'm writing my service to update a row using sequelize for PostGres. When I try out my query using a PSequel it works fine:

UPDATE "test_table" SET "test_col"=NULL WHERE "id"= '2'

But using sequelize it throws a 500 error:

db.TestTable.update({ testCol: NULL }, { where: { id: id } })
  .then((count) => {
    if (count) {
      return count;
    }
  });

My model does allowNull which I believe is what allows null values to be the default as well as set:

testCol: {
  type: DataTypes.INTEGER,
  allowNull: true,
  defaultValue: null,
  field: 'test_col'
},

Any other value but NULL works as expected. Is there a different method for setting null values?

like image 926
jerrylow Avatar asked May 09 '17 05:05

jerrylow


People also ask

How do you update null values in Sequelize?

Call an update function with just one null property probably is the reason of error 500 because it'll generate a incomplete UPDATE command (without SET ). Try to set omitNull: false or, if you cannot do this test, try to update this way: db. TestTable.

How do you update value in Sequelize?

First, you get an instance of the Model by calling the create() or findOne() method. Once you have the instance, you call the set() method to change the values of the instance. Then, you need to call the save() method on the instance to persist the changes to your table row.

What is update return Sequelize?

findById(params. userId); resolve(response); }); }); ANSWER: Update function of sequelize returns a number of affected rows (first parameter of result array).


2 Answers

From the looks of it, I think your issue is that you are using SQL's syntax for a null value ('NULL') where you should be using JS syntax ('null').

db.TestTable.update({ testCol: null }, { where: { id: id } })
  .then((count) => {
    if (count) {
      return count;
    }
  });

should work.

like image 180
Robert Taussig Avatar answered Sep 20 '22 23:09

Robert Taussig


Have you checked a more detailed error message in logs? I'd suggest you to add a promise catching error and then update your question.

For now, my guess is that you created your connection with omitNull: true. Call an update function with just one null property probably is the reason of error 500 because it'll generate a incomplete UPDATE command (without SET).

Try to set omitNull: false or, if you cannot do this test, try to update this way:

db.TestTable.testCol = null;
db.TestTable.save(['testCol']);

More info here.

like image 27
Michel Milezzi Avatar answered Sep 16 '22 23:09

Michel Milezzi