Search code examples
node.jspostgresqlknex.js

Knex primary key auto increment


I'm using knex to create a simple table in postgres database:

function up(knex, Promise) {
return knex.schema.createTableIfNotExists('communities', (table) => {

    table.increments('id').primary().unsigned();

    table.string('name', 255).notNullable();
    table.string('slug', 100).notNullable();

    table.timestamp('createdAt').defaultTo( knex.fn.now() );
    table.timestamp('updatedAt');
});

};

function down(knex, Promise) {
  return knex.schema.dropTableIfExists(tableName);
};

module.exports = {
    tableName,
    up,
    down
}

My problem is that table.increments('id').primary() creates a primary key that for default value has nextval('communities_id_seq'::regclass) and I can't do an insert without an id (even in raw sql).

Does anyone know how to make the id increment by default?


Solution

  • My problem was that the value for id was an empty string and not undefined or null, so that was braking the constraint for integer as data type.

    Hope it helps!