如何以编程方式 运行 sequelize 播种机?

How to programatically run sequelize seeders?

我是 NodeJS 和 Sequelize 的新手,我正在尝试在项目启动时执行 sequelize seeders。

这是我的种子函数之一的示例。

filePath: src/database/seeders/20220402125658-default-filters.js

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.bulkInsert('Filters', [
      {
        id: 'b16c15ce-9841-4ea5-95fb-0d21f8cd85f0', // TODO: use uuid4()
        name: 'Amount Filter',
        maxAmount: 200.0,
        minAmount: 0.2,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ]);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('Filters', null, bulkDeleteOptions);
  },
};

在我的 index.js 文件中,我正在执行 sequelize.sync() 以同步我的数据库模型。 这很好用,但我还想在同步完成后执行上面的种子代码。

filePath: src/database/index.js

db.sequelize.sync().then(() => {
// execute seeders here ...
});

你知道我该怎么做吗? 当我通过 npx 命令使用播种时,播种工作正常:npx sequelize-cli db:seed:all,但我想在项目启动时自动进行。

一个简单的方法可能是通过 Sequelize CLI 编写 运行s migrations/seeds 的脚本,并在您的 package.json 中添加一个调用它的 start 脚本,例如./run-migrations.sh && node .(或者可能只是 sequelize-cli db:migrate && sequelize-cli db:seed:all && node .)。然后只需 运行 npm run start 即可启动应用程序。


否则,从外观上看,Sequelize 具有 umzug library for programmatically applying migrations/seeds. See the comment in this issue 可以执行此操作的方法。

我会把代码复制到这里以防丢失:

/* <PROJECT_ROOT>/migrations.js */
var Umzug = require("umzug");
var models = require("./models");

var migrationsConfig = {
  storage: "sequelize",
  storageOptions: {
    sequelize: models.sequelize
    // modelName: 'SequelizeMeta' // No need to specify, because this is default behaviour
  },
  migrations: {
    params: [
      models.sequelize.getQueryInterface(),
      models.sequelize.constructor
    ],
    path: "./migrations", // path to folder containing migrations
    pattern: /\.js$/
  }
};

var seedsConfig = {
  storage: "sequelize",
  storageOptions: {
    sequelize: models.sequelize,
    modelName: 'SequelizeData' // Or whatever you want to name the seeder storage table
  },
  migrations: {
    params: [
      models.sequelize.getQueryInterface(),
      models.sequelize.constructor
    ],
    path: "./seeds", // path to folder containing seeds
    pattern: /\.js$/
  }
};

var migrator = new Umzug(migrationsConfig);
var seeder = new Umzug(seedsConfig);

module.exports = () => migrator.up().then(() => seeder.up());

/* <PROJECT_ROOT>/index.js */
var migrations = require("./migrations");

// Run migrations & seeds
migrations().then(function() {
  console.log("Migrations completed");
});