Sequelize how to return destroyed row
Asked Answered
H

1

7

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, ... }

Herrick answered 2/5, 2017 at 10:17 Comment(1)
Added some updates.Clan
C
15

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));
Clan answered 2/5, 2017 at 10:35 Comment(5)
Thank you Suhail.. have't implemented yet but I believe it will be fine... So are you sure that there is no way of retrieve deleted record without 2 query?Herrick
You could use a backup file, perhaps. I am not aware of any recovery tools available. But this is good.Clan
Actually update works that way with Postgres. See returnign: true optionAquileia
This answer is incorrect because of concurrency. The number of records during the find() and the destroy() operations aren't always the same.Seemaseeming
two queries have to be made just to get the returning data, not really optimize as I seeDemi

© 2022 - 2024 — McMap. All rights reserved.