0

I'm new with ExpressJS as I using Flask before.

In Flask, we can use Flask-SQLAlchemy as an ORM. Let's image if we have a model like this:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String())

then we can do database migration with this command using Alembic or Flask-migrate:

flask db migrate -m 'migrate comment

and then a migration file will be automatically generated on migrations folder. Then if we want to upgrade that, we can use this command:

flask db upgrade

And the changes will be implemented on our database.

And if we want to add a new column to the existing User table, let's say we want to add email column:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String())
    email = db.Column(db.String(120))

And the new column will be automatically generated on the migrations file after we run the: flask db migrate command, and then upgrade with: flask db upgrade

Now, I learn to use ExpressJS, I found Sequelize as a ORM for ExpressJS. And now I want to do same feature as I do before with Flask-SQLAlchemy and Alembic/Flask-Migrate.

I read the docs, if we want generates new model we can use this command:

npx sequelize-cli model:generate --name User --attributes username:string

and it will be generate model like this:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    username: DataTypes.STRING
  }, {});
  User.associate = function (models) {
    // associations can be defined here
  };
  return User;
};

And if we want to migrate we can use this:

npx sequelize-cli db:migrate

My questions are:

  1. Do we need to define id column on model:generate command..?
  2. What if we want to add a new column to an existing model, how to do that..?, any generate command to do that like model:generate like we created model before..?, or should we add new column manually on model file..?. So far, I just found we should add new column manually, and then we run model:generate command, and it will be generated an empty migration file, and then changes the migration file manually.
  3. Should we change the migration file manually if we want to make modifications to our existing models..? Any example codes or refer any tutorial how to do that would be very appreciated.
davidism
  • 121,510
  • 29
  • 395
  • 339
Tri
  • 2,722
  • 5
  • 36
  • 65
  • Take a look at this https://stackoverflow.com/questions/46357533/how-to-add-delete-new-columns-in-sequelize-cli. – Prabhjot Singh Kainth Dec 02 '19 at 10:29
  • After adding a new column to our model, we run the `sequelize migration:create --name name_of_your_migration`, and it will be generated new migration file, but just an empty migration file, and the new column that recently modifies not automatically detected on the migration file, we should typing the migration file manual to add a new column. – Tri Dec 02 '19 at 10:32

0 Answers0