【问题标题】:Sequelize migrations - run automatically when node application startsSequelize 迁移 - 节点应用程序启动时自动运行
【发布时间】:2019-09-24 07:22:22
【问题描述】:

我正在尝试让我的 Sequelize 迁移脚本在我的节点应用程序启动时自动运行。我已经通过运行 db:migrate 命令手动测试了迁移脚本以确保它们正常运行。

现在,我添加了这个文件来运行迁移脚本:

index.js

const {exec} = require('child_process');
const Sequelize = require('sequelize');
const config = require("config");

const sequelize = new Sequelize(config.get('postgres'));
async function start() {
    await new Promise((resolve, reject) => {
        const migrate = exec(
            'npm run db:migrate',
            {env: 'development'},
            (err, stdout, stderr) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            }
        );

        // Forward stdout+stderr to this process
        migrate.stdout.pipe(process.stdout);
        migrate.stderr.pipe(process.stderr);
    });
}

module.exports = {
    start: start
};

在 server.js 中:

async function start(appStarted) {
    logger.info('Initializing ...');

    // execute pending migrations
    logger.info('Migrating DB...');
    await require('../migrations').start();
    logger.info('DB Migration complete.');

当我启动应用程序时,它显示 Migrating DB... 并卡在那里。

我该如何解决这个问题?

【问题讨论】:

  • 您可以在 package.json 中添加如下内容:start-and-migrate: "NODE_ENV=development npm run db:migrate and node index.js"
  • 您最终解决了这个问题吗?在我的迁移已经运行后,我遇到了类似的问题。 db:migrate 命令卡在“没有执行迁移,数据库模式已经是最新的”。消息,从不解决任何问题。

标签: javascript node.js postgresql sequelize.js sequelize-cli


【解决方案1】:

您可以监听控制台消息并终止子进程,如下所示:

// Listen for the console.log message and kill the process to proceed to the next step in the npm script
    migrate.stdout.on('data', (data) => {
      console.log(data);
      if (data.indexOf('No migrations were executed, database schema was already up to date.') !== -1) {
        migrate.kill();
      }
    });

这将确保在您已经运行迁移时终止子进程。

【讨论】:

  • 解决方案来自link。由于我的声誉较低,我无法对其他人的回复添加评论。
猜你喜欢
  • 2020-08-20
  • 2012-03-06
  • 2021-12-31
  • 2014-05-03
  • 1970-01-01
  • 2021-04-29
  • 2016-04-03
  • 2020-03-10
相关资源
最近更新 更多