How can I truncate table and cascade with bulkDelete in Sequelize?

175
November 24, 2020, at 03:50 AM

I have a seed and I use bulkDelete with query interface. It's okay but I need to truncate table. I set truncate: true options and I get an error:

Cannot truncate a table referenced in a foreign key constraint (vexus_panel.visits, CONSTRAINT visits_ibfk_4 FOREIGN KEY (countryId) REFERENCES vexus_panel.countries (id))

And then I enable cascade like this: cascade: true but still not working

My code:

  down: async (queryInterface, Sequelize) => {
    /**
     * Add commands to revert seed here.
     *
     * Example:
     * await queryInterface.bulkDelete('People', null, {});
     */
    await queryInterface.bulkDelete("Countries", null, {
      truncate: true,
      cascade: true,
    });
  },

Error:

ERROR: Cannot truncate a table referenced in a foreign key constraint (vexus_panel.visits, CONSTRAINT visits_ibfk_4 FOREIGN KEY (countryId) REFERENCES vexus_panel.countries (id))

Docs: https://sequelize.org/master/class/lib/dialects/abstract/query-interface.js~QueryInterface.html#instance-method-bulkDelete

Update:

I found a solution.

  down: async (queryInterface, Sequelize) => {
    const { sequelize } = queryInterface;
    try {
      await sequelize.transaction(async (transaction) => {
        const options = { transaction };
        await sequelize.query("SET FOREIGN_KEY_CHECKS = 0", options);
        await sequelize.query("TRUNCATE TABLE Countries", options);
        await sequelize.query("SET FOREIGN_KEY_CHECKS = 1", options);
      });
    } catch (error) {
      console.log(error);
    }
  }
Answer 1

Disable the constraint, for the truncation

queryInterface.removeConstraint(vexus_panel.visits,visits_ibfk_4  )

And when you are done add it again

Rent Charter Buses Company
READ ALSO
AWS Amplify mock function

AWS Amplify mock function

I have frustratingly been trying to mock functions using AWS amplify

145
Trouble Connecting to Google Cloud IoT via MQTT with Node.js

Trouble Connecting to Google Cloud IoT via MQTT with Node.js

I'm trying to create a MQTT client that'll connect to the Google Cloud IoT Core, but for some reason, it won't connect at allHere's what I have so far

99
How does mongoose models have access to MongoDB database collections?

How does mongoose models have access to MongoDB database collections?

I want to understand what happens under the hood when Mongoose connects to a mongoDB database

62
Express not sending cross domain cookies

Express not sending cross domain cookies

I have a problem with sending cross domain session cookie and after searching I got even more confusedOriginally I had a client (Next app) on foo

100