Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize migrations

I am new to Sequelize and would like to know if anyone knows if there is a way to avoid the code duplication in Sequelize when using the migration functionality?

What I mean is that in the migration you would have something like this:

//migration-xyz.js
module.exports = {
  up: function(migration, DataTypes, done) {

      migration.createTable('Users',
      {
         name: DataTypes.STRING,
         surname: DataTypes.STRING
      });

  },

  down: function(migration, DataTypes, done) {
    // logic for reverting the changes
  }
}

But then the model would look something like this:

//user.js
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    name: DataTypes.STRING,
    surname: DataTypes.STRING
  });

  return User;
};

Is there a way to get rid of the code duplication?

Thanks for the help! :)

like image 424
cgiacomi Avatar asked Feb 03 '26 16:02

cgiacomi


1 Answers

As @WiredPrairie referenced in his/her comment, migrations and the attributes on a model are distinct things. Often we will create a model that has certain attributes and the associated migration to create the corresponding table. Later on more attributes will be added to the model and we will need to create a migration that adds columns for just the new attributes.

A way to remove the duplication would be to use sequelize.sync which creates your database from the model files. This has downsides though and should not be used on complex applications that are being deployed in different environments.

Maybe in the future the sequelize-cli will have a create:migration --model [modelfile] option where it will create the table for the corresponding model. This would have the same "duplication" of code but would make things a little faster.

like image 181
vpontis Avatar answered Feb 06 '26 07:02

vpontis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!