Sequelize - update record, and return result

Javascriptsequelize.js

Javascript Problem Overview


I am using sequelize with MySQL. For example if I do:

models.People.update({OwnerId: peopleInfo.newuser},
        {where: {id: peopleInfo.scenario.id}})
        .then(function (result) {
            response(result).code(200);
            
        }).catch(function (err) {
        request.server.log(['error'], err.stack);
       ).code(200);
    });

I am not getting information back if the people model was succesfully updated or not. Variable result is just an array with one element, 0=1

How can I know for certain that the record was updated or not.

Javascript Solutions


Solution 1 - Javascript

Here's what I think you're looking for.

db.connections.update({
  user: data.username,
  chatroomID: data.chatroomID
}, {
  where: { socketID: socket.id },
  returning: true,
  plain: true
})
.then(function (result) {
  console.log(result);   
  // result = [x] or [x, y]
  // [x] if you're not using Postgres
  // [x, y] if you are using Postgres
});

From Sequelize docs: The promise returns an array with one or two elements. The first element x is always the number of affected rows, while the second element y is the actual affected rows (only supported in postgres with options.returning set to true.)

Assuming you are using Postgres, you can access the updated object with result[1].dataValues.

You must set returning: true option to tell Sequelize to return the object. And plain: true is just to return the object itself and not the other messy meta data that might not be useful.

Solution 2 - Javascript

You can just find the item and update its properties and then save it. The save() results in a UPDATE query to the db

const job = await Job.findOne({where: {id, ownerId: req.user.id}});
if (!job) {
    throw Error(`Job not updated. id: ${id}`);
}

job.name = input.name;
job.payload = input.payload;
await job.save();

On Postgres:

Executing (default): UPDATE "jobs" SET "payload"=$1,"updatedAt"=$2 WHERE "id" = $3

Solution 3 - Javascript

Update function of sequelize returns a number of affected rows (first parameter of result array).

You should call find to get updated row

models.People.update({OwnerId: peopleInfo.newuser},
    {where: {id: peopleInfo.scenario.id}})
    .then(() => {return models.People.findById(peopleInfo.scenario.id)})
    .then((user) => response(user).code(200))
    .catch((err) => {
         request.server.log(['error'], err.stack);
      });

Solution 4 - Javascript

Finally i got it. returning true wont work in mysql , we have to use findByPk in order hope this code will help.

       return new Promise(function(resolve, reject) {
User.update({
        subject: params.firstName, body: params.lastName, status: params.status
    },{
        returning:true,
        where: {id:id }                             
    }).then(function(){
        let response = User.findById(params.userId);                      
        resolve(response);
    }); 

});

Solution 5 - Javascript

same thing you can do with async-await, especially to avoid nested Promises You just need to create async function :)

const asyncFunction = async function(req, res) {
    try {
        //update 
        const updatePeople = await models.People.update({OwnerId: peopleInfo.newuser},
                                    {where: {id: peopleInfo.scenario.id}})
        if (!updatePeople) throw ('Error while Updating');
        // fetch updated data
        const returnUpdatedPerson =  await models.People.findById(peopleInfo.scenario.id)
        if(!returnUpdatedPerson) throw ('Error while Fetching Data');
        res(user).code(200);
    } catch (error) {
        res.send(error)
    }
} 

Solution 6 - Javascript

There is another way - use findByPk static method and update not-static method together. For example:

let person = await models.People.findByPk(peopleInfo.scenario.id);
if (!person) {
  // Here you can handle the case when a person is not found
  // For example, I return a "Not Found" message and a 404 status code
}
person = await person.update({ OwnerId: peopleInfo.newuser });
response(person).code(200);

Note this code must be inside an asynchronous function.

Solution 7 - Javascript

You can fetch the model to update first, and call set() then save() on it. Returning this object will give you the updated model.

Although this might not be the shortest way to do it, I prefer it because you can handle not found and update errors separately.

const instance = await Model.findOne({
  where: {
    'id': objectId
  }
});

if (instance && instance.dataValues) {
  instance.set('name', objectName);
  return await instance.save(); // promise rejection (primary key violation…) might be thrown here
} else {
  throw new Error(`No Model was found for the id ${objectId}`);
}

Solution 8 - Javascript

If you're using postgres and updating one row.

  try {
    const result = await MODELNAME.update(req.body, {
      where: { id: req.params.id },
      returning: true
    });
    if (!result) HANDLEERROR()
    const data = result[1][0].get();
  
    res.status(200).json({ success: true, data });
  } catch (error) {
    HANDLEERROR()
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmiga500View Question on Stackoverflow
Solution 1 - JavascriptnickangView Answer on Stackoverflow
Solution 2 - JavascriptDavid DehghanView Answer on Stackoverflow
Solution 3 - JavascriptTilekbekov YrysbekView Answer on Stackoverflow
Solution 4 - JavascriptAnoop P SView Answer on Stackoverflow
Solution 5 - JavascriptBharat SuryawanshiView Answer on Stackoverflow
Solution 6 - Javascriptns16View Answer on Stackoverflow
Solution 7 - JavascriptFrelonGuepeView Answer on Stackoverflow
Solution 8 - JavascriptBasanta KcView Answer on Stackoverflow