Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: Destroy/Delete all records in the table

I am using Mocha for Unit tests.

When testing begins, I would like to delete all the previous records in a table.

What I have tried:

db.User.destroy({ force: true }).then(() => {
}).then(() => done());


db.User.destroy(
    {where: undefined},
    {truncate: false}
).then(() => {
    return 
}).then(() => done());


db.User.destroy({}).then(() => {
    return db.User.bulkCreate(users)
}).then(() => done());

I keep getting the following error:

 Error: Missing where or truncate attribute in the options parameter of model.destroy.

How do I delete/destroy all the records in a table?

like image 527
user1107173 Avatar asked Dec 03 '16 20:12

user1107173


People also ask

How do I delete all data from a table 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.

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.

What is truncate Sequelize?

destory({ truncate: true }), it delete all data in table.

What is paranoid false in Sequelize?

Sequelize supports the concept of paranoid tables. A paranoid table is one that, when told to delete a record, it will not truly delete it. Instead, a special column called deletedAt will have its value set to the timestamp of that deletion request.


3 Answers

You can try using

db.User.destroy({
  where: {},
  truncate: true
})
like image 144
maheshiv Avatar answered Nov 12 '22 13:11

maheshiv


I was able to solve this problem with the code:

table.sync({ force: true });

This is a safer solution than the one proposed in maheshiv's answer.

like image 8
jokermt235 Avatar answered Nov 12 '22 13:11

jokermt235


It works for me: db.User.truncate()

like image 2
Максим Коваль Avatar answered Nov 12 '22 13:11

Максим Коваль