Search code examples
postgresqlknex.js

While using Knex.js I made a migration and seed, but the seed data dose not show up in the PostgreSQL database


So I had to make a new table and seed with seed data for a project I'm working on. When I run the migrations I have no problems. I run the seeds I have no problems, but when I look into the PostgreSQL database for the data that's supposed to be in there like all the other seeds is not. For some reason it did NOT add the data and I cannot figure out why that would happen. If someone can help me find a solution to this would be great. Code and Screenshot below:

  1. Migration
 exports.up = function (knex) {
  return knex.schema.createTable('alliance', (table) => {
    table.increments('alliance_id').primary()
    table.string('alliance_name')
    table.string('description')
    table.integer('user_id')
    table
      .foreign('user_id')
      .references('user_id')
      .inTable('users')
      .onDelete('cascade')
  })
}

exports.down = function (knex) {
  return knex.schema.dropTable('alliance')
}
  1. seed
const alliances = require('../seed-data/alliance-data')

exports.seed = function (knex) {
  return knex
    .raw('TRUNCATE TABLE alliance RESTART IDENTITY CASCADE')
    .then(function () {
      return knex('alliance').insert(alliances)
    })
}
  1. Seed Data
module.exports = [
  {
    alliance_id: 0,
    alliance_name: 'test 1',
    description: 'testing 123',
  },
]
  1. Knex Config
const path = require('path')

require('dotenv').config()

const {
  DATABASE_URL = 'postgresql://postgres@localhost/postgres',
} = process.env

module.exports = {
  development: {
    client: 'postgresql',
    connection: DATABASE_URL,
    pool: { min: 0, max: 100 },
    migrations: {
      directory: path.join(__dirname, 'src', 'db', 'migrations'),
    },
    seeds: {
      directory: path.join(__dirname, 'src', 'db', 'seeds'),
    },
  },

  production: {
    client: 'postgresql',
    connection: DATABASE_URL,
    pool: { min: 0, max: 100 },
    migrations: {
      directory: path.join(__dirname, 'src', 'db', 'migrations'),
    },
    seeds: {
      directory: path.join(__dirname, 'src', 'db', 'seeds'),
    },
  },

  test: {
    client: 'sqlite3',
    connection: {
      filename: ':memory:',
    },
    migrations: {
      directory: path.join(__dirname, 'src', 'db', 'migrations'),
    },
    seeds: {
      directory: path.join(__dirname, 'src', 'db', 'seeds'),
    },
    useNullAsDefault: true,
  },
}
  1. Dbeaver Screenshot

  2. screenshot of dbeaver with no data


Solution

  • The solution to this issue is to make sure you're seeds and migrations are in the correct order.