Search code examples
node.jsherokumigrationsequelize.js

sequelize migrations in heroku


Can somebody please give me some complete examples for sequelize migrations for nodejs as the actual documentation itself doesn't give the complete example of how it is to be done.

or may be give a complete example of some other module that can be used and best practise of how to be use in heroku?

Thanks


Solution

  • When you initialize sequelize locally by running:

    sequelize -i
    

    a migration folder, config folder, and config.json inside the config folder are created. That json file is where you set the environments of your application. Here is an example of a config.json file.

    {
      "development": {
      "username": "postgres",
      "password": "password",
      "database": "dbname",
      "host": "100.0.0.0",
      "dialect":"postgres",
      "protocol":"postgres",
      "port":"xxxx"
     },
      "staging": {
      "username": "dbusername",
      "password": "dbpassword",
      "database": "db",
      "host": "host",
      "dialect":"postgres",
      "protocol":"postgres",
      "port":"xxxx"
      },
      "production": {
      "username": "dbusername",
      "password": "dbpassword",
      "database": "db",
      "host": "dbhost",
      "dialect":"postgres",
      "protocol":"postgres",
      "port":"xxxx"
      }
    }
    

    The production object is where you set your heroku production app database variables. You can access them by running the following in the command line:

    heroku config --app production-app-name
    

    All the variables will be in the database_url config var you set.

    When you're ready to run a migration, all you run in the command line then is:

    heroku run sequelize db:migrate --env production -m --app production-app-name. 
    

    --env will be whichever database object in config.json you want migrated.

    Instead of embedding passwords in a file, use this handy sequelize capability:

    "production": {
      "use_env_variable": "DATABASE_URL"
    }