EntityMetadataNotFoundError: No metadata for x was found.

See original GitHub issue

Issue Description

My project has 2 seperate connection datasources. One is to a readonly mysql database, the other is a postgres database.

Everything on the mysql database works fine. But I’m having issues with the postgres database.

In my index.ts file where I spin up my server, I initialize the postgres db datasouce

pgDataSource.initialize();

And here is pgDataSource

import 'reflect-metadata';
import 'dotenv-safe/config';
import { DataSource } from 'typeorm';
import path from 'path';
import Score from '../entities/Score';

const pgDataSource = new DataSource({
  name: 'favourites',
  type: 'postgres',
  url: process.env.DATABASE_URL,
  logging: true,
  synchronize: true,
  migrations: [path.join(__dirname, './migrations/*')],
  entities: [Score],
});

export const Manager = pgDataSource.manager;
export const ScoreRepository = pgDataSource.getRepository(Score);

export default pgDataSource;

At this point, everything seems fine, it creates a table in my database with the Score entity, so the connection exists and it acknowledges that there is an Entity as it creates the corresponding table.

Here is my Score entity

import { ObjectType, Field, Int } from 'type-graphql';
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm';

@ObjectType()
@Entity({ database: 'pp_favourites', name: 'score' })
class Score extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn()
  id!: number;

  @Field(() => Int)
  @Column()
  propertyId!: number;
}

export default Score;

Actual Behavior

When I run this query

await ScoreRepository.createQueryBuilder().getMany()

In a Query decorator function, I get the No metadata for \"Score\" was found. error

Although, if I run it through a useMiddleware decorator, it strangely works?

My Environment

Dependency Version
Operating System macOS Catalina
Node.js version v16.13.0
Typescript version 4.5.4
TypeORM version 0.3.6

Additional Context

I’ve tried

  1. Adding @Resolver(Score) as a decorator to the ShortlistResolver
  2. Removing the dist folder
  3. creating a new database and new connection
  4. Logged Manager.connection.entityMetadatas from pgDataSource which shows there are no entity’s, despite being defined.

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql yes
nativescript no
oracle no
postgres yes
react-native no
sap no
spanner no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, and I know how to start.
  • ✖️ Yes, I have the time, but I don’t know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✅ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:5

github_iconTop GitHub Comments

3reactions
harshrawat66commented, Sep 30, 2022

The following solution works. Modify the files as shown below

tasks.repository.ts

import { Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { CreateTaskDto } from './create-task.dto';
import { TaskStatus } from './task-status.enum';
import { Task } from './task.entity';

@Injectable()
export class TaskRepository extends Repository<Task> {
  constructor(private dataSource: DataSource) {
    super(Task, dataSource.createEntityManager());
  }

  async createTask({ title, description }: CreateTaskDto): Promise<Task> {
    const task = this.create({
      title,
      description,
      status: TaskStatus.OPEN,
    });

    await this.save(task);
    return task;
  }
}

tasks.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Task } from './task.entity';
import { TasksController } from './tasks.controller';
import { TaskRepository } from './tasks.repository';
import { TasksService } from './tasks.service';

@Module({
  imports: [TypeOrmModule.forFeature([Task])],
  controllers: [TasksController],
  providers: [TasksService, TaskRepository],
})
export class TasksModule {}

tasks.service.ts

import { Injectable, NotFoundException } from '@nestjs/common';
import { TaskStatus } from './task-status.enum';
import { CreateTaskDto } from './create-task.dto';
import { GetTaskFilterDto } from './get-task-filter.dto';
import { TaskRepository } from './tasks.repository';
import { InjectRepository } from '@nestjs/typeorm';
import { Task } from './task.entity';

@Injectable()
export class TasksService {
  constructor(private readonly tasksRepository: TaskRepository) {}

  async getTaskById(id: string): Promise<Task> {
    const record = this.tasksRepository.findOne({ where: { id } });
    if (!record) {
      throw new NotFoundException();
    }
    return record;
  }

  createTask(createTaskDto: CreateTaskDto): Promise<Task> {
    return this.tasksRepository.createTask(createTaskDto);
  }
}
1reaction
DanMoultoncommented, Nov 3, 2022

I’m seeing the same error, but it’s frustrating since it only happens when trying to write to a remote MySQL database that has the exact same schema as my local MySQL database:

NotFoundException: No metadata for "Role" was found.
    at /home/dan/Disk/Development/maa-ml-esg-monorepo/modules/api/src/auth/role/role.service.ts:74:28
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Role is already present in my entites array so I don’t know what’s going on…

Edit: It turns out I was getting this error since the write operation was happening on startup, and I wasn’t awaiting for my datasources to initialize. Adding await fixed it:

await ReadDataSource.initialize();
await WriteDataSource.initialize();
Read more comments on GitHub >

github_iconTop Results From Across the Web

No metadata for "User" was found using TypeOrm
Inserting a new user into the database... { EntityMetadataNotFound: No metadata for "User" was found. at new EntityMetadataNotFoundError ...
Read more >
EntityMetadataNotFound: No metadata for "User" was found.
Hello, I'm trying to setup a new project using the latest release and the ormconfig.yml options. I'm following the documentation and ...
Read more >
typeorm entitymetadatanotfounderror: no metadata for was ...
Solution for EntityMetadataNotFound: No metadata for was found The entity is a Typescript class that maps to a table in the database. If...
Read more >
Fix for EntityMetadataNotFound: No metadata was found in ...
Solution for EntityMetadataNotFound: No metadata for was found. The entity is a Typescript class that maps to a table in the database.
Read more >
typeorm/typeorm - Gitter
Inserting a new user into the database... { EntityMetadataNotFound: No metadata for "User" was found. at new EntityMetadataNotFoundError ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found