运行MIKRO ORM迁移创建命令时遇TypeError错误求助
问题描述
执行Mikro ORM迁移创建命令时,出现错误:
TypeError: Cannot read properties of undefined (reading 'reduce')
当前使用的Mikro ORM配置文件如下:
import { Options } from '@mikro-orm/core'; import path from 'path'; import { BeforeCreateUpdateSubscriber } from './path-to-subscriber'; // 根据实际路径调整 const config: Options = { host: process.env.HOST, port: 5432, entities: ["dist/src/core/**/*.entity.js"], entitiesTs: ["src/core/**/*.entity.ts"], dbName: process.env.DB_NAME, type: "postgresql", user: process.env.DB_USERNAME, password: process.env.DB_PASSWORD, baseDir: path.resolve(), // defaults to `process.cwd()`, subscribers: [new BeforeCreateUpdateSubscriber()], migrations: { tableName: "mikro_orm_migrations", // name of database table with log of executed transactions path: "./dist/src/migrations", pathTs: "./src/migrations", glob: "!(*.d).{js,ts}", // how to match migration files (all .js and .ts files, but not .d.ts) transactional: true, // wrap each migration in a transaction disableForeignKeys: false, // wrap statements with `set foreign_key_checks = 0` or equivalent allOrNothing: true, // wrap all migrations in master transaction dropTables: true, // allow to disable table dropping safe: false, // allow to disable table and column dropping snapshot: false, // save snapshot when creating new migrations emit: "ts", // migration generation mode }, debug: true, }; export default config;
排查与解决步骤
验证实体文件路径
确认entities和entitiesTs配置的路径是否能正确匹配到你的实体文件。可以尝试简化路径规则,比如改为"dist/**/*.entity.js"和"src/**/*.entity.ts",避免因层级过深或glob匹配规则问题导致实体未被加载——实体加载失败是触发这类reduce错误的常见原因。检查环境变量加载情况
确保process.env中的数据库相关变量(HOST、DB_NAME、DB_USERNAME、DB_PASSWORD)已正确注入。可以在配置文件开头添加console.log打印这些变量值,确认没有出现undefined的情况。排查订阅者实现问题
配置中直接实例化了BeforeCreateUpdateSubscriber,请检查该订阅者的代码是否存在初始化异常,比如构造函数中是否有未正确赋值的属性,或者继承的Mikro ORM订阅者类方法是否实现正确。可以临时注释掉subscribers配置项,重新执行迁移命令,如果错误消失,说明问题出在订阅者代码上。确认迁移目录存在
检查migrations.path和migrations.pathTs指向的目录是否已创建。如果目标目录不存在,Mikro ORM在处理迁移文件时可能抛出异常,手动创建src/migrations和dist/src/migrations目录后再试。更新或回退Mikro ORM版本
部分版本的Mikro ORM在特定配置组合下存在已知bug,尝试更新到最新稳定版,或者回退到之前能正常工作的版本,验证是否能解决该错误。
内容的提问来源于stack exchange,提问作者Pujan Shakya

