【问题标题】:Can knex.js be used without migrations/seeding? Is there something wrong with this knex.js code?可以在没有迁移/播种的情况下使用 knex.js 吗?这个 knex.js 代码有问题吗?
【发布时间】:2016-07-18 18:54:39
【问题描述】:

使用 knex.js 的规范方式似乎是创建迁移以定义模式,然后在普通 node.js 代码中插入到所述模式中。

有没有办法不使用迁移?我可以使用普通 node.js 代码中的knex.schema.createTable(...) 函数吗?有没有关于这类事情的文档?

编辑:我最初写这个问题是因为我认为我无法从我的正常代码库中执行knex.schema.createTable(...) 函数。现在看来我根本无法在任何代码中正确使用 knex。如果我使用迁移为 SQLite3 数据库生成架构,它可以工作,但我似乎永远无法在迁移或其他方式中插入或查询数据。

我的迁移文件:

exports.up = function(knex, Promise) {
    return Promise.all([
        knex.schema.createTableIfNotExists('test', function(table){
            console.log("creating user table");
            table.increments('id');
            table.text('test');
        })
    ]);
};

exports.down = function(knex, Promise) {
    return Promise.all([
        knex.schema.dropTableIfExists('test')
    ]);
};

knexfile.js:

module.exports = {
    development: {
        client:       "sqlite3",
        connection: {
            filename: "devel.db"
        },
        useNullAsDefault: true
    },
    deployment: {
        client:       "sqlite3",
        connection: {
            filename: "deploy.db"
        },
        useNullAsDefault: true
    }
};

还有我写的 mocha/chai 测试:

const chai      = require("chai");
var knex        = require("knex")({ client: "sqlite3", connection: { filename: "devel.db" }, useNullAsDefault: true });

var expect      = chai.expect;

// The tests.
describe("db", ()=> {
    it("Simple connect, query, and destroy.", ()=> {
        knex('test').insert({ test: 'wow' })
        .catch(function(e){
            console.error(e);
        });
    });
});

【问题讨论】:

  • 当然。只要数据库存在,您就可以随心所欲地进行操作(knex 中的迁移、liquibase 中的迁移、ansible 中的任务等)。

标签: javascript node.js knex.js


【解决方案1】:

您的迁移工作正常。在您的测试中,您需要返回 knex 对象才能执行它。

describe("db", ()=> {
  it("Simple connect, query, and destroy.", ()=> {
    return knex('test').insert({ test: 'wow' })
      .catch(function(e){
        console.error(e);
      });
  });
});

在回答实际问题时,是的,您可以。该代码类似于迁移代码,但需要调用 then() 或 catch() 来执行它。 Knex 文档涵盖了这一点,但还不是很清楚。以下是在迁移文件之外修改架构的示例:

knex.schema.table('test', function (table) {
  table.string('foo');
  table.string('baa');
})
.catch(function(err) {
  console.log(err);
});

我想不出很多时候修改数据库架构而不迁移会更好,但这取决于您的应用程序。

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 2022-06-14
    • 2020-12-06
    • 2018-05-05
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多