I'm trying to get a basic setup working using TypeORM, and getting this error following the setup.
Here is a REPL (just do yarn install && yarn db:dev followed by yarn db:migrate && yarn start to reproduce the error)
Inserting a new user into the database... { EntityMetadataNotFound: No metadata for "User" was found. at new EntityMetadataNotFoundError (/Users/admin/work/typeorm-naming-strategy/src/error/EntityMetadataNotFoundError.ts:9:9) at Connection.getMetadata (/Users/admin/work/typeorm-naming-strategy/src/connection/Connection.ts:313:19) at /Users/admin/work/typeorm-naming-strategy/src/persistence/EntityPersistExecutor.ts:77:55 at Array.forEach (<anonymous>) at EntityPersistExecutor.<anonymous> (/Users/admin/work/typeorm-naming-strategy/src/persistence/EntityPersistExecutor.ts:71:30) at step (/Users/admin/work/typeorm-naming-strategy/node_modules/typeorm/persistence/EntityPersistExecutor.js:32:23) at Object.next (/Users/admin/work/typeorm-naming-strategy/node_modules/typeorm/persistence/EntityPersistExecutor.js:13:53) at /Users/admin/work/typeorm-naming-strategy/node_modules/typeorm/persistence/EntityPersistExecutor.js:7:71 at new Promise (<anonymous>) at __awaiter (/Users/admin/work/typeorm-naming-strategy/node_modules/typeorm/persistence/EntityPersistExecutor.js:3:12) name: 'EntityMetadataNotFound', message: 'No metadata for "User" was found.' } 35 Answers
Adding answer bit late but its very common error.
There are two main reasons for above error. In OrmConfig,
- You have used *.ts instead of *.js. For example,
entities: [__dirname + '/../**/*.entity.ts'] <-- Wrong It should be
entities: [__dirname + '/../**/*.entity.js'] - entities path is wrong. Make sure, entities path is defined according to dist folder not src folder.
The problem is on ormConfig
Please try to use this:
entities: [__dirname + '/../**/*.entity.{js,ts}'] 3In my case I had forgotten to add new entity ( User in your case ) to app.module.ts . Here is the solution that worked for me:
// app.module.ts @Module({ imports: [ TypeOrmModule.forRoot({ ... entities: [User] ... }), ... ], }) 3If your app is using the latest DataSource instead of OrmConfig (like apps using the latest version of typeorm (0.3.1 the moment i'm writing theses lines)), make sure to call initialize() method of your DataSource object inside your data-source.ts file before using it anywhere in your app.
in my case, i was changing one EmployeeSchema to EmployeeEntity, but i forgot the entity annotation on it:
@Entity() export class Employee { Following will ensure that the file extensions used by TypeORM are both .js and .ts
entities: [__dirname + '/../**/*.entity.{js,ts}'] change this in your config file.
In my case i forgot to use connection.connect() method after creation of connection and got same error when using manager.find().
enable autoLoadEntities in app.module.ts
imports: [UserModule, TypeOrmModule.forRoot({ autoLoadEntities: true }) ] 1Make sure you have established a connection with the database before using the entities. In my case, I was using the AppDataSource before it was initialized. Here is how I fixed it:
import "reflect-metadata"; import { DataSource } from "typeorm"; import { Season } from "src/models/Season"; const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "postgres", password: "postgres", database: "test-db", synchronize: false, logging: false, entities: [Season], migrations: [], subscribers: [], }); AppDataSource.initialize() .then(async () => { console.log("Connection initialized with database..."); }) .catch((error) => console.log(error)); export const getDataSource = (delay = 3000): Promise<DataSource> => { if (AppDataSource.isInitialized) return Promise.resolve(AppDataSource); return new Promise((resolve, reject) => { setTimeout(() => { if (AppDataSource.isInitialized) resolve(AppDataSource); else reject("Failed to create connection with database"); }, delay); }); }; And in your services where you want to use the DataSource:
import { getDataSource } from "src/config/data-source"; import { Season } from "src/models/Season"; const init = async (event) => { const AppDataSource = await getDataSource(); const seasonRepo = AppDataSource.getRepository(Season); // Your business logic }; You can also extend my function to add retry logic if required :)
I got this err message, but i solved in a different way, it could also happen when you already have a table called "users" for example, and your model User is not with the same columns and configs as your table, in my case my table had a column called posts with a default value, and my model hadn't that default value set up, so before you check the entities directory on the ormconfig.json i highly recommend you check if your models are with the same properties and configs as your database table
I got the same issue and later found I haven't call the functionality to connect the DB. Just by calling the connection fixed my issue.
export const AppDataSource = new DataSource({ type: 'mysql', host: process.env.MYSQL_HOST, .... }); let dataSource: DataSource; export const ConnectDb = async () => { dataSource = await AppDataSource.initialize();And use this to connect in your function.
Another occasion I got a similar message when I run $ npm test without properly mocking Jest.spyOn() method and fixed it by:
jest.spyOn(db, 'MySQLDbCon').mockReturnValueOnce(Promise.resolve()); const updateResult = {} as UpdateResult; jest.spyOn(db.SQLDataSource, 'getRepository').mockReturnValue({ update: jest.fn().mockResolvedValue(updateResult), } as unknown as Repository < unknown > );for the new version of typeORM you must register the entity folder and the file extension
export const AppDataSource = new DataSource({ entities: ["dirname/**.ts"], }); in the example I used ts, but you can switch to js if that's your case.
in case you use the ormconfig file
{ "entities":["/**.ts"], } I believe my issue was caused by accidentally having both ormconfig.json and ormconfig.ts
1I'll contribute to this list of answers. In my case, I'm using a fancy-pants IDE that likes to auto-transpile the ts code into js without my knowledge. The issue I had was, the resulting js file was no bueno. Killing these auto-gen'd files was the answer.
The relevant bit of my ormconfig looks like:
{ ... "entities": ["src/entity/**/*.ts", "test/entity-mocks/**/*.ts"], "migrations": ["src/migration/**/*.ts"], "subscribers": ["src/subscriber/**/*.ts"] ... } Actually, I even tried the methods above to also include transpiled js files if they exist and I got other weird behavior.
I've tried all the solutions above, changing the typeORM version solved it for me.
Just in case someone runs into the same problem i had. I had to do two different things going against me:
I was missing the declaration of entity in ormConfig:
ormConfig={ ..., entities: [ ..., UserEntity ] } And since i was making changes (afterwards) to an existing entity, the cache was throwing a similar error. The solution for this was to remove the projects root folders: dist/ folder. Thou this might only be a Nest.js + TypeOrm issue.
In my case the entity in question was the only one giving the error. The rest of entities worked fine.
The automatic import failed to write correctly the name of the file.
import { BillingInfo } from "../entity/Billinginfo"; instead of
import { BillingInfo } from "../entity/BillingInfo"; The I for Info should be capital. The IDE also failed to show any errors on this import.
This error can also come up if you have a nodemon.json file in your project.
So after including your entity directory for both build and dev in the entities array
export const AppDataSource = new DataSource({ type: 'mysql', host: DB_HOST_DEV, port: Number(DB_PORT), username: DB_USER_DEV, password: DB_PASSWORD_DEV, database: DB_NAME_DEV, synchronize: false, logging: false, entities: [ process.env.NODE_ENV === "prod" ? "build/entity/*{.ts,.js}" : "src/entity/*{.ts,.js}", ], migrations: ["src/migration/*.ts"], subscribers: [], })
and still getting this error, remove the nodemon.json file if you have it in your project
ForMe , i have set error path cause this problem
my error code like this
and then i check the entities path . i modify the path to correct. then the typeorm working
Besides the @Entity() annotation, with typeorm version 0.3.0 and above also don't forget to put all your entities into your DataSource:
export const dataSource = new DataSource({ type: "sqlite", database: 'data/my_database.db', entities: [User], ... ... }) 1I was facing a similar issue, in my case I was using NestJS version 9.0.0.
In app.module while importing typeORM module, one of the properties autoLoadEntities was turned to false. So locally when I was trying to connect to DB, it was throwing me this error while writing a find() query.
Correct way to import typeORM:
TypeOrmModule.forRoot({ type: 'mongodb', host: process.env.DB_HOST || 'localhost', port: parseInt(process.env.DB_PORT) || 27017, username: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, database: process.env.DB_DATABASE, ssl: false, autoLoadEntities: true, synchronize: true, logging: true, }), I had the same issue, I used this: autoLoadEntities: true, in the config file instead of: entities: [__dirname + '/..//.entity.{js,ts}'],*** as seen in this github link:
1"No Metadata" error on TypeORM could be a LOT of causes. But in most of the cases the Entity was writen wrong or the database connection is not being succesful. I wrote this article trying to cover most of the cases.
my fail was that instead of using Models I used Requests. Requests are loaded earlier so it end it undefined. Try to move your Model Class to Models
Add your entity in orm.config.ts file.
entities: [empData,user], 1I omitted this @Entity() decorator on the entity class. So immediately I fixed this, and it worked for me. Example:
import { ObjectType, Field, ID } from '@nestjs/graphql'; import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; @ObjectType() @Entity() export class Message { @Field((type) => ID) @PrimaryGeneratedColumn('uuid') id: string; @Field() @Column() conversationId: string; @Field() @Column() sender: string; } For me it was two things, while using it with NestJS:
- There was two entities with the same name (but different tables)
Once I fixed it, the error still happened, then I got to point two:
- Delete the dist/build directory
Not sure how the build process works for typeorm, but once I deleted that and ran the project again it worked. Seems like it was not updating the generated files.
In my case I've provided a wrong db password. Instead of receiving an error message like "connection to db failed" I've got the error message below.
EntityMetadataNotFound: No metadata for "User" was found.
Using TypeORM with NestJS, for me the issue was that I was setting the migrations property of the TypeOrmModuleOptions object for the TypeOrmModuleAsyncOptions useFactory method, when instead I should've only set it on the migrations config, which uses the standard TypeORM DataSource type.
This is what I ended up with:
typeorm.config.ts
import { DataSource } from 'typeorm'; import { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions, } from '@nestjs/typeorm'; const postgresDataSourceConfig: TypeOrmModuleOptions = { ... // NO migrations property here // Had to add this as well autoLoadEntities: true, ... }; export const typeormAsyncConfig: TypeOrmModuleAsyncOptions = { useFactory: async (): Promise<TypeOrmModuleOptions> => { return postgresDataSourceConfig; }, }; // Needed to work with migrations, not used by NestJS itself export const postgresDataSource = new DataSource({ ...postgresDataSourceConfig, type: 'postgres', // Instead use it here, because the TypeORM Nest Module does not care for migrations // They must be done outside of NestJS entirely migrations: ['src/database/migrations/*.ts'], }); migrations.config.ts
import { postgresDataSource } from './typeorm.config'; export default postgresDataSource; And the script to run TypeORM CLI was
"typeorm-cli": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli -d ./src/database/migrations.config.ts"
Try this one. Should never fall
DB_ENTITIES=[dist/**/*.entity.js] 