Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column to an existing table in Node.js & Knex

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.

like image 213
ezg Avatar asked Mar 15 '20 05:03

ezg


2 Answers

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

like image 170
Isaac Pak Avatar answered Oct 06 '22 00:10

Isaac Pak


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>');
  })
like image 32
DylanA Avatar answered Oct 06 '22 00:10

DylanA