How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
NestJS · TypeScript/React

Fix QueryFailedError: relation "users" does not exist in NestJS

This error means TypeORM tried to query a database table that has not been created yet because migrations have not been run. Common causes include forgetting to run migrations, synchronize being false in production, or migration files not being included in the build. Fix it by running pending migrations before starting the app.

Reading the Stack Trace

QueryFailedError: relation "users" does not exist at PostgresQueryRunner.query (node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:219:19) at SelectQueryBuilder.loadRawResults (node_modules/typeorm/query-builder/SelectQueryBuilder.js:1042:25) at SelectQueryBuilder.executeEntitiesAndRawResults (node_modules/typeorm/query-builder/SelectQueryBuilder.js:973:26) at SelectQueryBuilder.getRawAndEntities (node_modules/typeorm/query-builder/SelectQueryBuilder.js:936:23) at SelectQueryBuilder.getMany (node_modules/typeorm/query-builder/SelectQueryBuilder.js:863:17) at UserRepository.find (node_modules/typeorm/repository/Repository.js:198:29) at UserService.findAll (src/user/user.service.ts:14:22) at UserController.getAll (src/user/user.controller.ts:10:28) at /node_modules/@nestjs/core/router/router-execution-context.js:46:28 at /node_modules/@nestjs/core/router/router-proxy.js:9:23

Here's what each line means:

Common Causes

1. Migrations not executed

The migration files exist but have not been run against the target database, so tables are missing.

// ormconfig.ts
{
  migrations: ['dist/migrations/*.js'],
  synchronize: false, // Correct for prod, but migrations must be run manually
}

2. Migration files excluded from build

The TypeScript compiler or bundler does not include migration files in the dist/ output.

// tsconfig.build.json
{
  "exclude": ["src/migrations"] // Accidentally excluded migrations
}

3. Using synchronize: true in development only

The schema was auto-synced in development but production uses migrations, and the migration for this table was never created.

// Only works with synchronize: true, no migration file exists
@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;
}

The Fix

Set migrationsRun: true to automatically run pending migrations when the application starts. This ensures the database schema is always up to date. For CI/CD, also run migrations explicitly before deployment.

Before (broken)
// app.module.ts
TypeOrmModule.forRoot({
  type: 'postgres',
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/migrations/*.js'],
  synchronize: false,
})
After (fixed)
// app.module.ts
TypeOrmModule.forRoot({
  type: 'postgres',
  host: process.env.DB_HOST,
  database: process.env.DB_NAME,
  entities: ['dist/**/*.entity.js'],
  migrations: ['dist/migrations/*.js'],
  migrationsRun: true, // Auto-run pending migrations on startup
  synchronize: false,
})

// Generate migration: npx typeorm migration:generate -d dist/data-source.js src/migrations/CreateUsers
// Or run manually: npx typeorm migration:run -d dist/data-source.js

Testing the Fix

import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User } from './user.entity';

describe('UserService', () => {
  let service: UserService;
  const mockRepo = {
    find: jest.fn().mockResolvedValue([{ id: 1, name: 'Alice' }]),
    findOne: jest.fn(),
    save: jest.fn(),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        { provide: getRepositoryToken(User), useValue: mockRepo },
      ],
    }).compile();

    service = module.get<UserService>(UserService);
  });

  it('returns all users', async () => {
    const users = await service.findAll();
    expect(users).toHaveLength(1);
    expect(mockRepo.find).toHaveBeenCalled();
  });

  it('handles QueryFailedError gracefully', async () => {
    mockRepo.find.mockRejectedValue(new Error('relation "users" does not exist'));
    await expect(service.findAll()).rejects.toThrow('relation "users" does not exist');
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nestjs-typeorm-migration,git add src/app.module.ts src/user/__tests__/user.service.spec.ts,git commit -m "fix: enable migrationsRun and ensure migration files are built",git push origin fix/nestjs-typeorm-migration

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm run build
      - run: npx typeorm migration:run -d dist/data-source.js
        env:
          DB_HOST: localhost
          DB_PORT: 5432
      - run: npm test -- --coverage

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Generate the migration with typeorm migration:generate.
  2. Verify the migration file is included in the build output.
  3. Run typeorm migration:run against the target database.
  4. Set migrationsRun: true for automatic migration on startup.
  5. Run tests, open a PR, merge after CI, and verify schema in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Never. synchronize: true can drop columns and data when entities change. Always use migrations in production to have controlled, reversible schema changes.

Run 'typeorm migration:revert -d dist/data-source.js' to undo the last migration. Always write a down() method in your migrations to support rollbacks.