Sequelize - update record, and return result

sequelize update query
sequelize update 2019
sequelize update all
sequelize update not working
sequelize update affected rows
sequelize update one instance
sequelize update if changed
sequelize update best practices

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

models.People.update({OwnerId: peopleInfo.newuser},
        {where: {id:}})
        .then(function (result) {

        }).catch(function (err) {
        request.server.log(['error'], err.stack);

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.

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

  user: data.username,
  chatroomID: data.chatroomID
}, {
  where: { socketID: },
  returning: true,
  plain: true
.then(function (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.

Sequelize's Update Method — example included, Today I am going to talk about the update method in Sequelize with update returning: true then update method will return the number of rows� This makes my code to hung.. the update is never done and a timeout happens. What I mean is that the Sequelize update is never resolved if I want to return it ! All my other Sequelize code is working perfectly ! Any hep will be very appreciate it :) Node: 12.16.0 || Sequelize: 5.21.6 || pg: 7.18.2

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:}})
    .then(() => {return models.People.findById(})
    .then((user) => response(user).code(200))
    .catch((err) => {
         request.server.log(['error'], err.stack);

update not returning the instance? � Issue #6757 � sequelize , update method is not returning correctly the model instance (the query run correctly) this.db.models. update that row by keeping Status='Success', Everything is going well model.field = value; model = await;. Model.update. Updates all instances that match a query. Takes two parameters: the first parameter contains the info you want to update. The second parameter contains the query for which instances to update. Like findOrCreate, it returns a promise for an array. The first element of the array is the number of rows that were affected.

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:}});
if (!job) {
    throw Error(`Job not updated. id: ${id}`);
} =;
job.payload = input.payload;

On Postgres:

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

Using `Returning` with Sequelize and Postgres � GitHub, Sequelize uses an option called returning to specify which data returns sure we update the proper instance in our database returning: true, });. Update and Destroy do not work that way. So you cannot, but there is a way. Model.find({ where: {} }).then((result) => { return Model.destroy({where: ..}) .then((u) => {return result}); }); Here we are returning a promise as Model.destroy which will resolve to result object received from the call to Model.find.

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 {
        const updatePeople = await models.People.update({OwnerId: peopleInfo.newuser},
                                    {where: {id:}})
        if (!updatePeople) throw ('Error while Updating');
        // fetch updated data
        const returnUpdatedPerson =  await models.People.findById(
        if(!returnUpdatedPerson) throw ('Error while Fetching Data');
    } catch (error) {

sequelizeJS, So I am trying to understand the return value sequelize.update provides. Here is my query: - sequelize.query( "UPDATE user set password_hash = ''" … In this article we will discuss what an API is, what it means to be RESTful, and how to implement these using Node.js. The Node.js packages we will be using will be Express for our API endpoints

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) {
        subject: params.firstName, body: params.lastName, status: params.status
        where: {id:id }                             
        let response = User.findById(params.userId);                      


Model, When true , the first returned value of aggregateFunction is cast to dataType and Fields to update if row key already exists (on duplicate key update)? (only� sequelize.query('SELECT 1', { // A function (or false) for logging your queries // Will get called for every SQL query that gets sent // to the server. logging: console.log, // If plain is true, then sequelize will only return the first // record of the result set. In case of false it will return all records.

Instance, Returns true if this instance has not yet been persisted to the database In its most basic form set will update a value stored in the underlying dataValues object. const [results, metadata] = await sequelize.query("UPDATE users SET y = 42 WHERE x = 12"); // Results will be an empty array and metadata will contain the number of affected rows. In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results.

Inserting, updating and destroying, Finds an instance that matches the specified query. If no such instance exists, it will create one. This method is a little funny - it returns a promise for an array! Sequelize bulk update with inner join. Each e-mail address corresponds to a user, so in changing the e-mail address you are attempting to change the user associated with that item. x is in development. [ Natty] python How to update multiple records at once (bulk update) in django API By: Mic 1.

Node.js MySQL Update, Update Table. You can update existing records in a table by using the "UPDATE" statement: The result object returned from the example above looks like this:. Sequelize. Sequelize is a promise-based ORM for Node.js. It works with PostgreSQL, MySQL, SQLite and MSSQL dialects and features solid transaction support, relations, read replication and more. Object Relational Mapping (ORM) is a technique of accessing a relational database from an object-oriented language. In this tutorial we work with MySQL.

  • I am using MySQL. I will test it with. Thanks for reply
  • I was not able to make it work with MySql. I guess this is only Postgresql feature :(
  • Also, despite what the docs say, I get undefined as the first parameter and the number of affected rows as the second parameter (using sqlite). To fix this I did result = result.filter(Boolean); before processing anything.
  • Is there a way to specify returned columns? I'm working with Postgress
  • what does mean x in "[x, y] if you are using Postgres" ?
  • So it seems the only way is to call find immediately after the update?
  • anyway you should use find function.
  • you can call find function first, then do update with this object without using where
  • if you're using PostgreSQL you can define returning option to true that returns affected rows
  • This is the cleanest solution that works universally. Thanks.