Auto-create mysql table with StrongLoop

后端 未结 8 820
栀梦
栀梦 2021-02-07 11:39

I am trying to use Strongloop with MySql but cannot figure out how to migrate or automatically create tables into a MySql database.

Is there at least a way to export the

相关标签:
8条回答
  • 2021-02-07 12:35

    In the same kind of issue, if you need to automatically create a database, you can use the createDatabase option in your dataSource JSON file.

      "mysql": {
        "host": "localhost",
        "port": 0,
        "database": "db",
        "username": "root",
        "password": "",
        "name": "mysql",
        "connector": "mysql",
        "debug": false,
        "createDatabase": true
      }
    

    So you don't need to write yourself the queries to create the base. Hope it helps.

    0 讨论(0)
  • 2021-02-07 12:35

    jduhls answer is beautiful, but I needed to tweak it slightly to add some static data into tables. Here's my tweaked version, along with an example of loading data into a simple SystemSettings table (id, settingName, settingValue):

    var async = require('async');
    
    var SYSTEM_SETTINGS = [
      {
        "settingName": "mustPayInAdvance",
        "settingValue": "false",
      }
    ];
    
    module.exports = function(app) {
        var path = require('path');
        var models = require(path.resolve(__dirname, '../model-config.json'));
        var datasources = require(path.resolve(__dirname, '../datasources.json'));
        var modelUpdates = [];
    
        function buildModelListForOperation(){
            Object.keys(models).forEach(function(key) {
                if (typeof models[key].dataSource != 'undefined') {
                    if (typeof datasources[models[key].dataSource] != 'undefined') {
                        modelUpdates.push({operation: app.dataSources[models[key].dataSource], key: key});
                    }
                }
            });
        }
    
        function createStaticData() {
            app.models.SystemSettings.create(SYSTEM_SETTINGS, function(err, created) {
                if (err) 
                    throw err;
                else
                    console.log('Sample data was imported.');
            });
        }
    
        function processModelsAndData(operationType) {
            buildModelListForOperation();
    
            // Create all models
            async.each(modelUpdates, function(item, callback) {
                item.operation[operationType](item.key, function (err) {
                    if (err) throw err;
                    console.log('Model ' + item.key + ' migrated');
                    callback();
                });
            }, function (err) {
                if (err) throw err;
                createStaticData();
            });    
        }
    
        //TODO: change to 'autoupdate' when ready for CI deployment to production
        processModelsAndData('automigrate');
    };
    
    0 讨论(0)
提交回复
热议问题