0

I am using Strongloop to create a RESTful API in Node.js. I configured the database connection and the connection test is ok.

Now what i am trying is importing my models from my database to Strongloop. I use the "Discover models" option but when i click on it a window appears but the tables remain blank.

However I am sure that my database is contening a lot of tables. (I am using a ClearDB database with an Heroku account)

Can someone please help me? Thank you

1 Answers1

4

I found I had to define the database that I wanted to discover here

ds.discoverModelDefinitions({ schema: 'YOUR-DB-NAME' }

var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var loopback = require('loopback');

var outputPath = path.resolve(__dirname, '../common/models');
var ds = loopback.createDataSource('mysql', require('../server/datasources').local);

ds.discoverModelDefinitions({ schema: 'YOUR-DB-NAME' }, function (err, models) {

    var count = models.length;
  
  _.each(models, function(model){
    ds.discoverSchema(model.name, {  associations: true }, function(err, schema){
      var outputName = outputPath + '/' +schema.name + '.json';
      fs.writeFile(outputName, JSON.stringify(schema, null, 2), function(err) {
        if(err) {
          console.log(err);
        } else {
          console.log("JSON saved to " + outputName);
        }
      });
      fs.writeFile(outputPath + '/' + schema.name + '.js', jsFileString(schema.name), function(err) {
        if (err) throw err;
        console.log('Created ' + schema.name + '.json file');
      });
      count = count - 1;
      if (count === 0) {
        console.log("DONE!", count);
        ds.disconnect();
        return;
      }
    });
  })
});


function capitaliseFirstLetter(string) {
    return string.charAt(0)
        .toUpperCase() + string.slice(1);
}

function jsFileString(model_name) {
    return '' + 'module.exports = function(' + capitaliseFirstLetter(model_name) + ') {\n' + '\t\n' + '};';
}
dalelane
  • 2,746
  • 1
  • 24
  • 27
Jozzhart
  • 1,312
  • 11
  • 9
  • It should be `schema: 'YOUR-SCHEMA-NAME'`. Db name is provided when creating datasource i.e. ds as `var ds = loopback.createDataSource('postgresql', { "host": "hostname", "port": 5432, "database": "testdb", "password": "password", "user": "username", });` – raevilman Aug 23 '17 at 12:33
  • @raevilman in mysql, as it shows in the answer code, schemas and databases are the same. It's not like postgres – ffflabs Oct 18 '18 at 15:15