Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add, Delete new Columns in Sequelize CLI

I've just started using Sequelize and Sequelize CLI

Since it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?

For example, I want to a new column 'completed' to Todo model. I'll add this column to models/todo.js. Whats the next step?

I tried sequelize db:migrate

not working: "No migrations were executed, database schema was already up to date."

like image 461
Gijo Varghese Avatar asked Sep 22 '17 05:09

Gijo Varghese


People also ask

How do I delete 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.


2 Answers

If you are using sequelize-cli you need to create the migration first. This is just a file that tells the engine how to update the database and how to roll back the changes in case something goes wrong. You should always commit this file to your repository

$ sequelize migration:create --name name_of_your_migration 

The migration file would look like this:

module.exports = {   up: function(queryInterface, Sequelize) {     // logic for transforming into the new state     return queryInterface.addColumn(       'Todo',       'completed',      Sequelize.BOOLEAN     );    },    down: function(queryInterface, Sequelize) {     // logic for reverting the changes     return queryInterface.removeColumn(       'Todo',       'completed'     );   } } 

And then, run it:

$ sequelize db:migrate 
like image 179
Maria Ines Parnisari Avatar answered Oct 21 '22 23:10

Maria Ines Parnisari


If you want to add multiple columns to the same table, wrap everything in a Promise.all() and put the columns you'd like to add within an array:

module.exports = {   up: (queryInterface, Sequelize) => {     return Promise.all([       queryInterface.addColumn(         'tableName',         'columnName1',         {           type: Sequelize.STRING         }       ),       queryInterface.addColumn(         'tableName',         'columnName2',         {           type: Sequelize.STRING         }       ),     ]);   },    down: (queryInterface, Sequelize) => {     return Promise.all([       queryInterface.removeColumn('tableName', 'columnName1'),       queryInterface.removeColumn('tableName', 'columnName2')     ]);   } };  

You can have any column type supported by sequelize https://sequelize.readthedocs.io/en/2.0/api/datatypes/

like image 44
thedanotto Avatar answered Oct 22 '22 00:10

thedanotto