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:
- Do we need to define id column on
model:generate
command..? - 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 runmodel:generate
command, and it will be generated an empty migration file, and then changes the migration file manually. - 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.