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
Here's what each line means:
- at PostgresQueryRunner.query (node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:219:19): PostgreSQL rejected the query because the 'users' table does not exist in the database.
- at UserRepository.find (node_modules/typeorm/repository/Repository.js:198:29): TypeORM's Repository.find() generated a SELECT query against the non-existent table.
- at UserService.findAll (src/user/user.service.ts:14:22): Your user service at line 14 calls the repository which fails because the schema is not applied.
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.
// 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,
})
// 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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Generate the migration with typeorm migration:generate.
- Verify the migration file is included in the build output.
- Run typeorm migration:run against the target database.
- Set migrationsRun: true for automatic migration on startup.
- 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.