node.js - 使用迁移 API 时 Knex 迁移不起作用

标签 node.js migration knex.js

我是 knex 迁移的新手,在过去的两天里,我一直在努力让它工作,但没有任何反应。我正在尝试使用 knex.migration 对象以编程方式运行我的迁移。

首先使用 cli,我在 migrations 目录中创建了一个迁移文件。这是它的内容:

exports.up = function(knex, Promise) {
   return Promise.all([
        knex.schema.createTable('users', function (table) {
            table.increments('id').primary();
            table.string('username');
            table.string('password');
            table.string('email');
            table.string('name');
            table.timestamp('date');
        }),
    ]);
};

exports.down = function(knex, Promise) {

};

然后根据我的代码初始化 Knex 对象:

var knex = Knex({
        client:'sqlite3',
        connection:{
            filename: './knex.sqlite'
        }
    });

然后我执行迁移:

knex.migrate.latest().then(()=>{
        // console.log()
    }).catch(err =>{
        // 
    });

但绝对没有任何反应。我的迁移文件从未执行过,也没有错误或警告消息。所以我不知道从哪里开始寻找问题。当我查看我的 sqlite 数据库时,我可以看到已创建表 knex_migrationsknex_migrations_locksqlite_sequence

那么我这里做错了什么?有什么我想念的吗? 感谢您的任何建议

最佳答案

不需要使用 CLI 工具。有时由于其限制而无法使用它,在这种情况下,确实可以直接使用迁移 API,如下所示:

const knex = require('knex')({
    // Here goes the Knex config
});

const migrationConfig = {
    directory: __dirname + './migrations',
}

console.info('Running migrations in: ' + migrationConfig.directory);

knex.migrate.latest(migrationConfig).then(([batchNo, log]) => {
    if (!log.length) {
        console.info('Database is already up to date');
    } else {
        console.info('Ran migrations: ' + log.join(', '));
    }

    // Important to destroy the database, otherwise Node script won't exit
    // because Knex keeps open handles.
    knex.destroy();
});

原题有两个问题:

  1. 未指定迁移目录 - 在这种情况下,Knex 并不智能,它只会抛出错误而不做任何事情。 Knex 使用的默认值很可能不正确,因此最好指定它。

  2. knex.destroy() 丢失。在这种情况下,脚本将永远不会退出,因为 Knex 在数据库上保持打开的句柄,所以它看起来就像停滞不前。

上面的脚本还输出了更多日志信息以查看到底发生了什么。

关于node.js - 使用迁移 API 时 Knex 迁移不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304267/

相关文章:

node.js - 不在以下划线开头的文件夹中的文件的 Node glob 模式

node.js - gulp 中的任务继承,父级 gulpfile.js

svn - 如何迁移 svn :externals properties across a repository? 中的所有 URL

mysql - fatal error : Call to a member function num_rows() on boolean in C:\xamp\htdocs\project24\system\database\DB_driver. php 第 768 行

ruby-on-rails - Rails g 迁移不起作用

javascript - 循环中的异步调用延迟

javascript - httpOnly cookie 中的 JWT - AuthGuard 和 protected 路由(Node.js、Angular)

javascript - 如何更改 NodeJS、Express、Passport 中输入字段的名称属性?

sql - 如何在同一列中加入不同的 FK 值?

javascript - 使用 knex 插入数据库