Loopback discoverAndBuildModels not generating models

后端 未结 4 1346
鱼传尺愫
鱼传尺愫 2021-02-05 23:29

I\'m trying to get Loopback to discover and build my first table. I\'ve used the simple example on their page at the bottom here:

http://docs.strongloop.com/display/LB/D

4条回答
  •  [愿得一人]
    2021-02-06 00:06

    Seems that discovery scripts only shows the output and doesn't create the model files. I found some instructions on loopback docs:

    http://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases

    In section Basic Procedure, the second step:

    2. Use fs.writeFile() to save the output in common/models/model-name.json.

    So you can try the following approach:

    1. Setup your mysql data in yourloopbackproject/server/datasources.json file:
    {
      "db": {
        "name": "db",
        "connector": "memory"
      },
      "accountDs": {
        "host": "mysqlServerName",
        "port": 3306,
        "database": "databaseName",
        "username": "username",
        "password": "password!",
        "name": "accountDs",
        "connector": "mysql"
      }
    }
    
    1. Create the models folder if doesn't exist: yourloopbackproject/common/models.

    2. Create discovery-and-build.js script on yourloopbackproject/server/bin folder:

    var path = require('path');
    var fs = require('fs');
    var app = require(path.resolve(__dirname, '../server'));
    var outputPath = path.resolve(__dirname, '../../common/models');
    
    var dataSource = app.dataSources.accountDs;
    
    function schemaCB(err, schema) {
      if(schema) {
        console.log("Auto discovery success: " + 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);
          }
        });
      }
      if(err) {
        console.error(err);
        return;
      }
      return;
    };
    
    dataSource.discoverSchema('tableName',{schema:'schemaName'},schemaCB);
    

    This script is based on: http://www.reddit.com/r/strongloop/comments/2upy76/autodiscoveryjs_recipe/

    1. After the script execution you will find a .json file on models folder. Go to step 3 on Basic Procedure section: http://docs.strongloop.com/display/public/LB/Discovering+models+from+relational+databases

    2. Follow these steps to expose your model over REST: http://docs.strongloop.com/display/public/LB/Exposing+models+over+REST

    I hope this helps!

提交回复
热议问题