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

Devsullo
  • 864
  • 1
  • 9
  • 14

1 Answers1

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));
Itamar
  • 119
  • 1
  • 6
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • 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? – Devsullo May 02 '17 at 10:51
  • You could use a backup file, perhaps. I am not aware of any recovery tools available. But this is good. – Suhail Gupta May 02 '17 at 10:55
  • 2
    Actually `update` works that way with Postgres. See `returnign: true` option – Yaroslav Grishajev Jun 11 '19 at 08:46
  • 2
    This answer is incorrect because of concurrency. The number of records during the find() and the destroy() operations aren't always the same. – Quoc Vu Dec 13 '21 at 00:20