Loopback Automigration Scripts

December 10th, 2017 Javascript 445 views

Hey Guys, its been a long time I haven’t posted anything. I have been recently playing with Loopback API Framework. And planning to build a small App using Loopback + MySQL + VueJS. I am planning to keep posting updates on this. But for now just wanted to share this most important info which I wasn’t able to find on their official documentation.

It’s about migrating databases automatically. So you create the model using “lb model” command and some datasources like mongodb creates the tables immediately on creating the model. But for some datasources like MySQL, you have to create them manually or using an auto-migration script. This they have mentioned in their documentation but they haven’t given the exact script to execute. You have to read the full documentation and create your own script.

So I did some trial and error stuff and finally created these 2 scripts for different purposes.

automigrate.js
Executing this script creates all the tables in database automatically. It deletes the tables if they already exists. So be careful while executing it.

autoupdate.js
Executing this script alters/changes all the tables that have been modified manually from their specific JSON files. So it doesn’t effect the data but just alters the tables.

Follow the steps below to add these scripts and execute them.

Step 1:

Open terminal and enter below commands.

Step 2:

Now create 2 blank files named as below inside bin/ folder
automigrate.js
and
autoupdate.js

Step 3:

Open automigrate.js file in your favorite code editor and paste in below code.

Notice the lbTables array. The first 5 values in this array are the core tables which Loopback uses for it’s own purpose. The other values MY_TABLE_1, MY_TABLE_2 will be your own table names. Basically you have to go to common/models folder and check the .json files generated for your Models using “lb model” command. So you have to use those model names and add them in this Array.

Now you have to execute this script to generate the tables in your database. So use below command.

This will output Nan ‘mysql’ on your terminal. It means the tables are created successfully.

Step 4:

Open autoupdate.js file in your favorite code editor and paste in below code.

Again, notice the lbTables array. Update it as per your need. And run the command

And this will update your tables in database if you have changed/added/removed any fields in their respective .json files under common/modules folder.

Note: make sure you are in the root folder of your project before running any of these commands.

So these are the essential things to do when you create a Model using lb model command. As mentioned before, you don’t need it if the tables are generated automatically.

Leave your comments: