You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM报错EntityMetadataNotFoundError:找不到User元数据求助

EntityMetadataNotFoundError: No metadata for "User" was found. 问题排查与求助

我尝试了多种方法仍无法解决TypeORM的「EntityMetadataNotFoundError: No metadata for "User" was found.」错误,多次修改entities路径配置均无效,试过的配置包括:

  • entities: [__dirname + '/../**/*.entities.js']
  • entities: [__dirname + '/../**/*.entity.js']
  • entities: [__dirname + '/../**/*.entities.{js,ts}']
  • 直接导入User类:import User from "./src/entities/User"; 并配置 entities: [User];

相关代码配置

User实体代码

import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
} from "typeorm";

@Entity()
export default class User {

    @PrimaryGeneratedColumn()
    id!: number;

    @Column({ nullable: true })
    firstName: string;

    @Column({ nullable: true })
    lastName: string;
}

package.json配置

{
  "name": "my-nodejs-project",
  "version": "1.0.0",
  "description": "This project will consist in a node.js API REST project which will display \r a list of products",
  "main": "index.ts",
  "directories": {
    "test": "tests"
  },
  "scripts": {
    "test": "jest",
    "prettier": "prettier --check .",
    "prettier:write": "prettier --write .",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings=0",
    "lint:fix": "eslint . --fix --ext .js,.jsx,.ts,.tsx --max-warnings=0",
    "start": "nodemon --watch \"src/**\" --exec \"ts-node\" src/app.ts",
    "typeorm": "typeorm-ts-node-esm -d ormconfig.ts", 
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jest": "^27.5.2",
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "multer": "^1.4.5-lts.1",
    "pg": "^8.11.3",
    "tsconfig-paths": "^4.2.0",
    "tslib": "^2.6.2",
    "typeorm": "^0.3.17",
    "typescript": "^4.3.5"
  },
  
  "devDependencies": {
    "@types/cors": "^2.8.14",
    "@types/dotenv": "^8.2.0",
    "@types/multer": "^1.4.8",
    "cross-env": "^7.0.3",
    "eslint": "^7.32.0",
    "faker": "^5.5.3",
    "jest": "^27.0.6",
    "nodemon": "^2.0.12",
    "prettier": "^2.3.2",
    "supertest": "^6.1.4",
    "ts-jest": "^27.0.4",
    "ts-node": "^10.9.1"
  },
  "prettier": {
    "arrowParens": "always",
    "bracketSpacing": true,
    "embeddedLanguageFormatting": "auto",
    "htmlWhitespaceSensitivity": "css",
    "insertPragma": false,
    "jsxBracketSameLine": false,
    "jsxSingleQuote": false,
    "printWidth": 80,
    "proseWrap": "preserve",
    "quoteProps": "as-needed",
    "requirePragma": false,
    "semi": true,
    "singleQuote": false,
    "tabWidth": 4,
    "trailingComma": "es5",
    "useTabs": false,
    "vueIndentScriptAndStyle": false
  },
  "jest": {
    "verbose": true,
    "testEnvironment": "node",
    "transform": {
      "^.+\\.ts?$": "ts-jest"
    },
    "coveragePathIgnorePatterns": [
      "/node_modules/",
      "/src/migrations",
      "ormconfig.js"
    ],
    "preset": "ts-jest",
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "setupFiles": [
      "./src/testSetup.ts"
    ],
    "testTimeout": 20000,
    "collectCoverage": true,
    "coverageReporters": [
      "json-summary",
      "text",
      "cobertura",
      "lcov"
    ]
  },
  "eslintConfig": {
    "root": true,
    "ignorePatterns": [
      "node_modules",
      "coverage",
      ".vscode",
      ".github",
      "public",
      "build"
    ],
    "parser": "@typescript-eslint/parser",
    "plugins": [
      "@typescript-eslint"
    ],
    "extends": [
      "eslint:recommended",
      "plugin:@typescript-eslint/recommended"
    ]
  }
}

ormconfig.ts配置

import { DataSource } from "typeorm"
import User from "./src/entities/User";

export const connectionSource = new DataSource({
  migrationsTableName: 'migrations',
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'user',
  password: 'admin',
  database: 'products',
  logging: false,
  synchronize: true,
  name: 'default',
  entities: ["./src/entities/*{.ts,.js}'"],
  migrations: ['./src/migrations/*.ts'],
  subscribers: ['src/subscriber/**/*{.ts,.js}'],
});

entities是存放所有实体的文件夹名称,实在不知道还能尝试什么方法,恳请大家帮忙解决!


针对性解决建议

  1. 修复路径语法错误
    当前ormconfig.ts的entities路径存在语法错误,多了一个末尾单引号,修改为:

    entities: ["./src/entities/**/*.{ts,js}"]
    

    使用**匹配所有子目录,确保能扫描到实体文件。

  2. 适配ESM模块的路径解析
    由于你使用typeorm-ts-node-esm(ESM模式),__dirname无法直接使用,需手动导入路径模块处理:

    import { fileURLToPath } from 'url';
    import { dirname, join } from 'path';
    
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = dirname(__filename);
    
    export const connectionSource = new DataSource({
      // ...其他配置项
      entities: [join(__dirname, 'src/entities/**/*.{ts,js}')],
    });
    
  3. 验证实体导入与装饰器
    若使用直接导入实体类的方式,确保导入语句正确,且@Entity()装饰器未被遗漏:

    import User from "./src/entities/User";
    
    export const connectionSource = new DataSource({
      // ...其他配置项
      entities: [User],
    });
    
  4. 确认连接初始化流程
    应用启动时需优先初始化DataSource,再启动服务:

    import { connectionSource } from './ormconfig';
    import express from 'express';
    
    async function bootstrap() {
      await connectionSource.initialize();
      const app = express();
      // 配置路由等
      app.listen(3000);
    }
    
    bootstrap();
    

内容的提问来源于stack exchange,提问作者brian comas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:15:55