Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize how to return destroyed row

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

like image 928
Devsullo Avatar asked May 02 '17 10:05

Devsullo


People also ask

Does Sequelize destroy return anything?

Some Sequelize commands don't return anything (or at least not anything useful) by default. Sequelize uses an option called returning to specify which data returns from a commands like . destroy() or update() . Let's look at three common Sequelize commands and see how to handle the data returned by each.

How do you use destroy in Sequelize?

By default, Sequelize will assume the table uses an id column as its primary key. Now you can call destroy() from the Invoice model to delete a row by its id value: const count = await Invoice. destroy({ where: { id: 2 } }); console.

What is destroy in Sequelize?

To delete rows of data from your SQL table using Sequelize, you need to use the provided destroy() method. The destroy() method can be called from any Model or instance of your Model to delete rows from your table.

What does update in Sequelize return?

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


1 Answers

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));
like image 151
Suhail Gupta Avatar answered Sep 20 '22 12:09

Suhail Gupta