19

I'm using Node.js and Knex to build a service for my router. However, I can't figure out how to add a column to an existing table, any help would be appreciated. Also, I'm using PostgreSQL, but I don't think that matters for the question.

So, this is what I have for adding rows to the table:

insertData(knex, table, row) {
  return knex
    .insert(row)
    .into(table)
    .returning('*')
    .then(rows => {
      return rows[0];
    });
}

I'm guessing adding a column to the table would be something similar to this? I just can't figure out/find the solution.

felixmosh
  • 32,615
  • 9
  • 69
  • 88
ezg
  • 715
  • 2
  • 7
  • 20

4 Answers4

23

For migrations:

This was taken from this article

  1. First make a migration:

knex migrate:make add_new_column_to_table

  1. then in the migration update the file to:
exports.up = function(knex) {
  return knex.schema.table('<table name>', table => {
    table.string('<new column name>', 128);
  })
};

exports.down = function(knex) {
  return knex.schema.table('<table name>', table => {
    table.dropColumn('<new column name>');
  })
};
  1. then run the migration:

knex migrate:latest

Isaac Pak
  • 4,467
  • 3
  • 42
  • 48
9

The answers above are correct EXCEPT...

Make sure to write "knex.schema.alterTable" instead of "knex.schema.table".

Below is correct:

 return knex.schema.alterTable('<table name>', table => {
    table.dropColumn('<new column name>');
  })
DylanA
  • 141
  • 2
  • 2
  • 1
    Both are correct as one is an alias of the other. `alterTable` is more explicit. See https://github.com/knex/knex/issues/3990. – t7tran Jun 14 '22 at 23:54
6

you should use Schema Building function provided by Knex.js

Below is an example from its official documentation:

//Chooses a database table, and then modifies the table

knex.schema.table('users', function (table) {
  table.string('first_name');
  table.string('last_name');
})

//Outputs:
//alter table `users` add `first_name` varchar(255), add `last_name` varchar(255);
tcf01
  • 1,699
  • 1
  • 9
  • 24
1

1.run this :

knex migrate:make add_new_column_to_table

2.a new file will be created '20220524120511_dd_new_column_to_table.js'

use this code :


exports.up = async function (knex) {
    await knex.schema.table("table_name", (table) => {
    table.string("column_name", 128);
  });
};

exports.down = async function (knex) {
    await knex.schema.table("table_name", (table) => {
    table.dropColumn("column_name");
  });
};

  1. run this :

knex migrate:latest