How to update a record using sequelize for node? How to update a record using sequelize for node? express express

How to update a record using sequelize for node?


Since version 2.0.0 you need to wrap your where clause in a where property:

Project.update(  { title: 'a very different title now' },  { where: { _id: 1 } })  .success(result =>    handleResult(result)  )  .error(err =>    handleError(err)  )

Update 2016-03-09

The latest version actually doesn't use success and error anymore but instead uses then-able promises.

So the upper code will look as follows:

Project.update(  { title: 'a very different title now' },  { where: { _id: 1 } })  .then(result =>    handleResult(result)  )  .catch(err =>    handleError(err)  )

Using async/await

try {  const result = await Project.update(    { title: 'a very different title now' },    { where: { _id: 1 } }  )  handleResult(result)} catch (err) {  handleError(err)}

http://docs.sequelizejs.com/en/latest/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows


I have not used Sequelize, but after reading its documentation, it's obvious that you are instantiating a new object, that's why Sequelize inserts a new record into the db.

First you need to search for that record, fetch it and only after that change its properties and update it, for example:

Project.find({ where: { title: 'aProject' } })  .on('success', function (project) {    // Check if record exists in db    if (project) {      project.update({        title: 'a very different title now'      })      .success(function () {})    }  })


Since sequelize v1.7.0 you can now call an update() method on the model. Much cleaner

For Example:

Project.update(  // Set Attribute values         { title:'a very different title now' },  // Where clause / criteria          { _id : 1 }      ).success(function() {      console.log("Project with id =1 updated successfully!"); }).error(function(err) {      console.log("Project update failed !");     //handle error here });