6

db:seed:all私は今、1時間以上苦労してきましたが、ゆっくりとこれについて頭を悩ませています.

私は単純なモデルを持っています:

'use strict';
module.exports = function (sequelize, DataTypes) {
  var Car = sequelize.define('Cars', {
    name: DataTypes.STRING,
    type: DataTypes.INTEGER,
    models: DataTypes.INTEGER
  }, {
      classMethods: {
        associate: function (models) {
          // associations can be defined here
        }
      }
    });
  return Car;
};

これは移行中であり、sequelize db:migrate正常に動作するデータベースに移動します。

次に、シード ファイルを使用して 2 台の車を挿入します。だから私はコマンドを実行してsequelize seed:create --name insertCars 追加しましたbulkInsert

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.bulkInsert(
      'Cars',
      [
        {
          name: "Auris",
          type: 1,
          models: 500,
          createdAt: Date.now(), updatedAt: Date.now()
        },
        {
          name: "Yaris",
          type: 1,
          models: 500,
          createdAt: Date.now(), updatedAt: Date.now()
        }
      ]
    );
  },

  down: function (queryInterface, Sequelize) {
  }
};

実行するsequelize db:seed:allと、次のエラーが表示されます。

Loaded configuration file "config\config.json".
Using environment "development".
== 20160510132128-insertCars: migrating =======
Seed file failed with error: Cannot read property 'name' of undefined

これらのシーダーを実行した経験のある人はいますか? 参考までに、私の設定ファイルは次のとおりです。

{
  "development": {
    "username": "mydbdude",
    "password": "mydbdude",
    "database": "Cars",
    "host": "127.0.0.1",
    "dialect": "mssql",
    "development": {
      "autoMigrateOldSchema": true
    }
  },
  ....other configs
}

編集: db:migrate からの出力

Sequelize [Node: 5.9.1, CLI: 2.4.0, ORM: 3.23.0]

Loaded configuration file "config\config.json".
Using environment "development".
No migrations were executed, database schema was already up to date.
4

2 に答える 2

3

私はまだこれを機能させることができなかったので、私が使用したソリューションを投稿します。これはかなりうまく機能しますが、カスタムビルドです。

まず、シードするオブジェクトを含む JSON ファイルを作成しました。すなわち

dataSources: [
    {
        name: 'Pattern'
    },
    {
        name: 'Upload'
    }
]

次に、次のものを含むアプリケーションのサーバー側に を実装しseeder.jsました (もちろん、トリミングされたバージョン)

var models = require('./../models'),
sql = models.sequelize,
Promise = models.Sequelize.Promise;

var objects = require('./seed/objects'), //this is where my object file is
dataSources = objects.dataSources;


var express = require('express');

var seedDatabase = function () {
    var promises = [];
    promises.push(createDataSources());
    //more can be added to the promises

    return Promise.all(promises);
};

function createDataSources() {
    return models.sequelize
        .transaction(
            {
                isolationLevel: models.sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
            },
            function (t) {
                return models.DataSource
                    .findAll({
                        attributes: [
                            'id'
                        ]
                    })
                    .then(function (result) {
                        if (!result || result.length == 0) {
                            return models.DataSource
                                .bulkCreate(dataSources, { transaction: t })
                                .then(function () {
                                    console.log("DataSources created");
                                })
                        }
                        else {
                            console.log("DataSources seeder skipped, already objects in the database...");
                            return;
                        }
                    });
            })
        .then(function (result) {
            console.log("DataSources seeder finished...");
            return;
        })
        .catch(function (error) {
            console.log("DataSources seeder exited with error: " + error.message);
            return;
        });
};

module.exports = {
    seedDatabase: seedDatabase
}

これですべてのセットアップが完了seedDatabaseしました。次のように、アプリケーションの起動時にこの関数を使用して、シーダーを実行できます。

//includes and routes above, not interesting for this answer
try {
    umzug.up().then(function (migrations) {
        for (var i = 0; i < migrations.length; i++) {
            console.log("Migration executed: " + migrations[i].file);
        }

        console.log("Running seeder");
        seeder.seedDatabase().then(function () { //here I run my seeders
            app.listen(app.get('port'), function () {
                console.log('Express server listening on port ' + app.get('port'));
            });
        });
    });
}
catch (e) {
    console.error(e);
}

これで、アプリケーションを実行すると、シーダーはデータベースにオブジェクトが既に挿入されているかどうかをチェックします。その場合、シーダーはスキップされ、そうでない場合は挿入されます。

これが皆さんのお役に立てば幸いです。

于 2016-09-21T06:41:43.963 に答える