Search code examples
expressloopbackjsstrongloop

Loopback default models with a mysql database


I'm trying out loopback and noticed that in the model-config file it has a reference to 5 models that have their dataSource set to the memory database db:

  "User": {
    "dataSource": "db"
  },
  "AccessToken": {
    "dataSource": "db",
    "public": false
  },
  "ACL": {
    "dataSource": "db",
    "public": false
  },
  "RoleMapping": {
    "dataSource": "db",
    "public": false
  },
  "Role": {
    "dataSource": "db",
    "public": false
  }

Is that desired behaviour to keep the users, acl etc in the memory? If not, how can I port those models to mysql? I tried switching the dataSource to my mysql source but the server complains because the tables are not present.


Solution

  • Copy paste the following code in server/server.js. (preferably to the last)

    var appModels = ['User', 'AccessToken', 'ACL', 'RoleMapping', 'Role'];
    
    var ds = app.dataSources.mysqlDS;
    ds.isActual(appModels, function(err, actual) {
      if (!actual) {
        ds.autoupdate(appModels, function(err) {
          if (err) throw (err);
        });
      }
    });
    

    Don't forget to change the model's datasource to the new datasource in model-config.json. In the code replace the mysqlDS to your datasource.

    Cheers!

    Reference: https://loopback.io/doc/en/lb3/Creating-database-tables-for-built-in-models.html