K ACHARYA
K ACHARYA

Reputation: 43

How to get the fields and values of an updated row in Sequelize

My code for update a row in sequelize - MySQL - Express is as below

// Update an user
userController.update = function(req, res) {
  models.user.update(
  {
    user_name: req.body.name,
    user_address: req.body.address,
    user_email: req.body.email,
  }, {where: {user_id: req.params.id}, returning: true, plain: true})
  .then((user)=>{
    res.redirect("/users/show/"+user.user_id);
  })
  .catch((err)=>{
    console.log(err);
    res.render("../views/users/edit", {user: req.body});
  });   
};

But user.user_id is showing the value of undefined How to get the fields and values of an updated row in sequelize

Upvotes: 2

Views: 5930

Answers (2)

AbhinavD
AbhinavD

Reputation: 7282

update returns the number of rows affected as the first parameter. If you need the affected object, you can use spread

// Update an user
userController.update = function(req, res) {
  models.user.update(
  {
    user_name: req.body.name,
    user_address: req.body.address,
    user_email: req.body.email,
  }, {where: {user_id: req.params.id}, returning: true, plain: true})
  .spread((affectedCount, affectedRows) => {
    // use affectedRows here
  })
  .catch((err) => {
    console.log(err);
    res.render("../views/users/edit", {user: req.body});
  });   
};

If you want to use .then Use like this .then(function([ rowsUpdate, [usersUpdated] ]) {

Upvotes: 3

user10279088
user10279088

Reputation:

As of official doc, this is supported only for postgres with options.returning true

http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update

Upvotes: 1

Related Questions