Knex.js postgresql数据库连接

时间:2018-06-18 21:12:29

标签: node.js database postgresql express knex.js

我有点问题&这很可能是用户错误。我只是尝试使用Node/Express将我的Knex.js应用程序连接到数据库。我正在使用Postgres App

migrations/20180618143210_item.js

exports.up = function (knex, Promise) {
    knex.schema.createTable('items', (table) => {
        table.increments('id').primary();
        table.string('name');
    })
};

exports.down = function (knex, Promise) {
    knex.schema.dropTable('items')
};

knexfile.js

module.exports = {

  development: {
    client: 'postgresql',
    connection: {
      host : 'localhost',
      database: 'my_db',
      user: 'User',
      password: ''
    },
    migrations: {
      directory: __dirname + '/db/migrations'
    },
    seeds: {
      directory: __dirname + '/db/seeds/development'
    }
  },

  staging: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  },

  production: {
    client: 'postgresql',
    connection: {
      database: 'my_db',
      user:     'username',
      password: 'password'
    },
    pool: {
      min: 2,
      max: 10
    },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};

当我运行knex migrate:latest时,它会创建数据库,当连接到\dt数据库时,我可以看到以下my_db数据库表:

                  List of relations
 Schema |         Name         | Type  |    Owner
--------+----------------------+-------+-------------
 public | knex_migrations      | table | User
 public | knex_migrations_lock | table | User

当我select * from knex_migrations;我回来时:

 id |          name          | batch |       migration_time
----+------------------------+-------+----------------------------
  2 | 20180618143210_item.js |     1 | 2018-06-18 14:40:08.994-06

但是,如果我尝试运行类似select * from items的内容,则会出现ERROR: relation "items" does not exist错误。我在这里错过了什么吗?当我尝试为数据knex seed:run

播种时,会发生同样的错误

items.js

exports.seed = function(knex, Promise) {
  // Deletes ALL existing entries
  return knex('items').del()
    .then(function () {
      // Inserts seed entries
      return knex('items').insert([
        {id: 1, name: 'rowValue1'},
        {id: 2, name: 'rowValue2'},
        {id: 3, name: 'rowValue3'}
      ]);
    });
};

错误:error: relation "items" does not exist

1 个答案:

答案 0 :(得分:1)

我弄清楚为什么会这样。我没有从knex up& down功能。所以而不是:

exports.up = function (knex, Promise) {
    knex.schema.createTable('items', (table) => {
        table.increments('id').primary();
        table.string('name');
    })
};

exports.down = function (knex, Promise) {
    knex.schema.dropTable('items')
};

我需要:

exports.up = function (knex, Promise) {
    **return** knex.schema.createTable('items', (table) => {
        table.increments('id').primary();
        table.string('name');
    })
};

exports.down = function (knex, Promise) {
    **return** knex.schema.dropTable('items')
};