0
votes

The problem is the following: I have a database and schema designed in MySql, and I'm trying to import automaticaly to my api base in LoopBack the models to work with them. I have read the following help: http://loopback.io/doc/en/lb2/Discovering-models-from-relational-databases.html#additional-discovery-functions But It doesn't work.

I have tried, changing the INVENTORY for datalogger (name of table in my database.

var loopback = require('loopback');
var ds = loopback.createDataSource('mysql', {
"host": "localhost",
"port": 3306,
"database": "maintenancetooldb",
"username": "root",
"password": "Password_4567"
});

// Discover and build models from INVENTORY table
ds.discoverAndBuildModels('datalogger', {visited: {}, associations: true},
function (err, models) {
console.log(JSON.stringify(inv, null, 2));
// Now we have a list of models keyed by the model name
// Find the first record from the inventory
models.datalogger.findOne({}, function (err, inv) {
if(err) {
  console.error(err);
  console.log(JSON.stringify(inv, null, 2));
  return;
 }
console.log("\nInventory: ", inv);

// Navigate to the product model
// Assumes inventory table has a foreign key relationship to product table
inv.product(function (err, prod) {
  console.log("\nProduct: ", prod);
  console.log("\n ------------- ");
 });
 });
});

To be honest I'm lost, yesterday I used sequelize-auto for the first time, but today the requirements have been changed.

Thanks in advance for you help.

1

1 Answers

1
votes

Can you try this

var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var loopback = require('loopback');
var outputPath = '/home/rahul/Loopback/Helloworld/common/models';
var loopback = require('loopback');
var ds = loopback.createDataSource('mysql', {
  "host": "localhost",
  "port": 3306,
  "database": "XXX",
  "username": "XXX",
  "password": "XXX"
});
ds.discoverModelDefinitions({ schema: 'My-schema' }, function (err, models) {

    var count = models.length;

  _.each(models, function(model){
    //console.log(model.name);
    ds.discoverSchema(model.name, {  associations: false }, function(err, schema){ // instead of model.name just mention your table name
      //console.log("GG0");
      //console.log("GG"+schema.name);
      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', 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;
      }
    });
  })
});