简体   繁体   中英

Typeorm entities not working with javascript

I'm trying to create a project with typeorm with javascript, a connection works correctly, but typeorm can't find my entities.

I am following the example provided by the type documentation: https://typeorm.io/#/usage-with-javascript

app.js:

typeorm.createConnection({
  type: 'mysql',
  host: process.env.MYSQL_IP, // Docker Env
  port: process.env.MYSQL_INTERNAL_PORT,
  username: process.env.MYSQL_ROOT_USERNAME,
  password: process.env.MYSQL_ROOT_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  synchronize: true,
  entities: [
    require('./Model/TestSchema.js'),
  ],
}).then((connection) => {
  const app = express();

  app.use(cors(CorsConfigs));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(authentication);
  app.use(router);

  const testRepository = connection.getRepository('Category');
  const teste = { name: 'TypeScript' };

  app.listen(process.env.BACKEND_PORT, () => {
    console.log(`Rodando na porta: ${process.env.BACKEND_PORT.toString()}`);
  });
}).catch((error) => {
  console.log('Error: ', error);
});

Model/TestSchema.js:

module.exports = {
  name: 'Category',
  columns: {
    id: {
      primary: true,
      type: 'int',
      generated: true,
    },
    name: {
      type: 'string',
    },
  },
};

the connection is working correctly, the problem and when I run it shows me:

Error: RepositoryNotFoundError: No repository for "Category" was found. Looks like this entity is not registered in current "default" connection?

at new RepositoryNotFoundError (/app/src/error/RepositoryNotFoundError.ts:11:9)

at EntityManager.getRepository (/app/src/entity-manager/EntityManager.ts:919:19)

at Connection.getRepository (/app/src/connection/Connection.ts:346:29)

at /app/src/app.js:32:37

at processTicksAndRejections (internal/process/task_queues.js:93:5)

Maybe in

entities: [
  require('./Model/TestSchema.js'),
],

you need remove the .js extension on file path, smt like:

entities: [
  require('./Model/TestSchema'),
],

First, anyone who is using TypeOrm with javascript should read this article once, because in most places documentation is about how to use TypeOrm with typescript not javascript.

Abner, please change your TestSchema.js to this:

var EntitySchema = require("typeorm").EntitySchema;

module.exports = new EntitySchema({
  name: "Category", 
  tableName: "Category",
  columns: {
    id: {
      primary: true,
      type: 'int',
      generated: true,
    },
    name: {
      type: 'string',
    },
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM