Chinese Documentation : Creating a database schema from models

LoopBack auto-migration creates a database schema based on your application's models.  In relational databases, auto-migration creates a table for each model, and a column in the table for each property in the model.  Auto-migration creates tables for all models attached to a data source, including built-in models

Once you have defined a model, LoopBack can create or update (synchronize) the database schemas accordingly, if you need to adjust the database to match the models.  LoopBack provides two ways to synchronize model definitions with table schemas:

  • Auto-migrate: Automatically create or re-create the table schemas based on the model definitions. 
  • Auto-update: Automatically alter the table schemas based on the model definitions.
Icon

Auto-migration will drop an existing table if its name matches a model name. When tables with data exist, use auto-update to avoid data loss.

Auto-migrate

Icon

StrongLoop Arc enables you to perform auto-migration without coding.

See also: See also automigrate() in LoopBack API reference.

The following data sources support auto-migration:

Here’s an example of auto-migration.  Consider this model definition:

  • A table CUSTOMER_TEST.

  • A sequence CUSTOMER_TEST_ID_SEQUENCE for keeping sequential IDs.

  • A trigger CUSTOMER_ID_TRIGGER that sets values for the primary key.

Now suppose you decide to make some changes to the model. Here is the second version:

 

Running autoMigrate() once tables exist will drop and re-create tables and therefore data will be lost. To avoid this problem use auto-update().  Instead of dropping tables and recreating them, autoupdate() calculates the difference between the LoopBack model and the database table definition and alters the table accordingly. This way, the column data will be kept as long as the property is not deleted from the model.

For example:

To check if database changes are required, use the isActual() method. It accepts a callback argument that receives a Boolean value depending on database state:

  • False if the database structure outdated
  • True when data source and database is in sync
/server/script.js
dataSource.isActual(models, function(err, actual) {
    if (!actual) {
        dataSource.autoupdate(models, function(err, result) {
            ...
        });
    }
});