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."
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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With