Sequelize how to return destroyed row

Devsullo picture Devsullo · May 2, 2017 · Viewed 12.3k times · Source

Here is my code for deleting rows in database

Model.destroy({
  where: {
    ...
  }
}).then((response) => {
    console.log(response)
})

What I am getting in console.log is 0 or 1 whether record deleted or not..

Is it any way to return destroyed row in promise?

So response should be like this { id:123, ... }

Answer

Suhail Gupta picture Suhail Gupta · May 2, 2017

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.

So, let us say there is a function called deleteRow defined as:

function deleteRow() {
    return Model.find({
        where: { ...}
    }).then((result) => {
        return Model.destroy({ where: ..})
            .then((u) => { return result });
    });
}

You could use deleteRow as:

deleteRow().then(findResult => console.log(JSON.stringify(findResult));